From 206810c69db517a07f16f123567ef1c5fc0497e6 Mon Sep 17 00:00:00 2001 From: tom79 Date: Sat, 14 Oct 2017 14:36:48 +0200 Subject: [PATCH 01/46] Recyclerview beginning --- app/build.gradle | 1 + .../mastodon/activities/HashTagActivity.java | 38 ++- .../activities/ShowConversationActivity.java | 17 +- .../mastodon/drawers/StatusListAdapter.java | 248 +++++++------- .../fragments/DisplayStatusFragment.java | 126 +++---- .../etalab/mastodon/helper/CrossActions.java | 314 ++++++++++++++---- .../gouv/etalab/mastodon/helper/Helper.java | 10 + app/src/main/res/layout/fragment_accounts.xml | 5 +- app/src/main/res/layout/fragment_status.xml | 2 +- 9 files changed, 470 insertions(+), 291 deletions(-) diff --git a/app/build.gradle b/app/build.gradle index 692663481..8c9e3f6de 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -35,6 +35,7 @@ dependencies { compile 'com.android.support:design:26.0.2' compile 'com.android.support:support-v4:26.0.2' compile 'com.android.support:cardview-v7:26.0.2' + compile 'com.android.support:recyclerview-v7:26.0.2' compile 'com.loopj.android:android-async-http:1.4.9' compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' compile 'com.evernote:android-job:1.1.11' diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/HashTagActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/HashTagActivity.java index 10d51b8e2..3ab4c8722 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/HashTagActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/HashTagActivity.java @@ -21,6 +21,8 @@ import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; import android.view.MenuItem; import android.view.View; import android.widget.AbsListView; @@ -35,6 +37,7 @@ import fr.gouv.etalab.mastodon.asynctasks.RetrieveFeedsAsyncTask; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Status; import fr.gouv.etalab.mastodon.drawers.StatusListAdapter; +import fr.gouv.etalab.mastodon.fragments.DisplayStatusFragment; import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveFeedsInterface; import mastodon.etalab.gouv.fr.mastodon.R; @@ -93,7 +96,7 @@ public class HashTagActivity extends AppCompatActivity implements OnRetrieveFeed int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); - final ListView lv_status = (ListView) findViewById(R.id.lv_status); + final RecyclerView lv_status = (RecyclerView) findViewById(R.id.lv_status); tootsPerPage = sharedpreferences.getInt(Helper.SET_TOOTS_PER_PAGE, 40); mainLoader = (RelativeLayout) findViewById(R.id.loader); nextElementLoader = (RelativeLayout) findViewById(R.id.loading_next_status); @@ -123,23 +126,28 @@ public class HashTagActivity extends AppCompatActivity implements OnRetrieveFeed R.color.colorPrimaryD, R.color.colorPrimaryDarkD); } + final LinearLayoutManager mLayoutManager; + mLayoutManager = new LinearLayoutManager(this); + lv_status.setLayoutManager(mLayoutManager); + lv_status.addOnScrollListener(new RecyclerView.OnScrollListener() { + public void onScrolled(RecyclerView recyclerView, int dx, int dy) + { + if(dy > 0){ + int visibleItemCount = mLayoutManager.getChildCount(); + int totalItemCount = mLayoutManager.getItemCount(); + int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); + if(firstVisibleItem + visibleItemCount == totalItemCount ) { + if(!flag_loading ) { + flag_loading = true; + new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.TAG, tag,null, max_id, HashTagActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - lv_status.setOnScrollListener(new AbsListView.OnScrollListener() { - @Override - public void onScrollStateChanged(AbsListView view, int scrollState) { - - } - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if(firstVisibleItem + visibleItemCount == totalItemCount ) { - if(!flag_loading ) { - flag_loading = true; - new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.TAG, tag,null, max_id, HashTagActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - - nextElementLoader.setVisibility(View.VISIBLE); + nextElementLoader.setVisibility(View.VISIBLE); + } + } else { + nextElementLoader.setVisibility(View.GONE); } - } else { - nextElementLoader.setVisibility(View.GONE); } + } }); new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.TAG, tag,null, max_id, HashTagActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowConversationActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowConversationActivity.java index 60439e2a6..6d4dc92b9 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowConversationActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowConversationActivity.java @@ -25,6 +25,8 @@ import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MotionEvent; @@ -77,7 +79,7 @@ public class ShowConversationActivity extends AppCompatActivity implements OnRet private Status initialStatus; public static int position; private SwipeRefreshLayout swipeRefreshLayout; - private ListView lv_status; + private RecyclerView lv_status; private boolean isRefreshed; private TextView title; private ImageView pp_actionBar; @@ -179,13 +181,18 @@ public class ShowConversationActivity extends AppCompatActivity implements OnRet new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.ONESTATUS, statusId,null, false,false, ShowConversationActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); - lv_status = (ListView) findViewById(R.id.lv_status); + lv_status = (RecyclerView) findViewById(R.id.lv_status); + final LinearLayoutManager mLayoutManager; + mLayoutManager = new LinearLayoutManager(this); + lv_status.setLayoutManager(mLayoutManager); lv_status.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == android.view.MotionEvent.ACTION_UP) { - - if (lv_status.getLastVisiblePosition() == lv_status.getAdapter().getCount() -1 && lv_status.getFirstVisiblePosition() > 0 && + int visibleItemCount = mLayoutManager.getChildCount(); + int totalItemCount = mLayoutManager.getItemCount(); + int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); + if (firstVisibleItem + visibleItemCount == lv_status.getAdapter().getItemCount() -1 && firstVisibleItem > 0 && lv_status.getChildAt(lv_status.getChildCount() - 1).getBottom() <= lv_status.getHeight()) { swipeRefreshLayout.setRefreshing(true); @@ -267,7 +274,7 @@ public class ShowConversationActivity extends AppCompatActivity implements OnRet lv_status.setVisibility(View.VISIBLE); if( isRefreshed){ position = statuses.size()-1; - lv_status.setSelection(position); + lv_status.scrollToPosition(position); }else { lv_status.smoothScrollToPosition(position); } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java index 8777c2206..b500385fc 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java @@ -34,6 +34,7 @@ import android.os.CountDownTimer; import android.support.v4.content.ContextCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.PopupMenu; +import android.support.v7.widget.RecyclerView; import android.text.Html; import android.text.SpannableString; import android.text.method.LinkMovementMethod; @@ -45,7 +46,6 @@ import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; -import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; @@ -105,14 +105,13 @@ import static fr.gouv.etalab.mastodon.helper.Helper.changeDrawableColor; * Created by Thomas on 24/04/2017. * Adapter for Status */ -public class StatusListAdapter extends BaseAdapter implements OnPostActionInterface, OnTranslatedInterface, OnRetrieveFeedsInterface { +public class StatusListAdapter extends RecyclerView.Adapter implements OnPostActionInterface, OnTranslatedInterface, OnRetrieveFeedsInterface { private Context context; private List statuses; private LayoutInflater layoutInflater; private ImageLoader imageLoader; private DisplayImageOptions options; - private ViewHolder holder; private boolean isOnWifi; private int translator; private int behaviorWithAttachments; @@ -126,6 +125,7 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf private List pins; public StatusListAdapter(Context context, RetrieveFeedsAsyncTask.Type type, String targetedId, boolean isOnWifi, int behaviorWithAttachments, int translator, List statuses){ + super(); this.context = context; this.statuses = statuses; this.isOnWifi = isOnWifi; @@ -140,24 +140,117 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf - @Override - public int getCount() { - return statuses.size(); - } - - @Override - public Object getItem(int position) { - return statuses.get(position); - } - @Override public long getItemId(int position) { return position; } @Override - public int getViewTypeCount() { - return 2; + public int getItemCount() { + return statuses.size(); + } + + private class ViewHolderEmpty extends RecyclerView.ViewHolder{ + ViewHolderEmpty(View itemView) { + super(itemView); + } + } + + class ViewHolder extends RecyclerView.ViewHolder{ + LinearLayout status_content_container; + LinearLayout status_spoiler_container; + TextView status_spoiler; + Button status_spoiler_button; + CardView card_status_container; + TextView status_content; + TextView status_content_translated; + LinearLayout status_content_translated_container; + TextView status_account_username; + TextView status_account_displayname; + ImageView status_account_profile; + ImageView status_account_profile_boost; + ImageView status_account_profile_boost_by; + TextView status_favorite_count; + TextView status_reblog_count; + TextView status_toot_date; + TextView status_reblog_user; + Button status_show_more; + ImageView status_more; + LinearLayout status_document_container; + ImageView status_prev1; + ImageView status_prev2; + ImageView status_prev3; + ImageView status_prev4; + ImageView status_prev1_play; + ImageView status_prev2_play; + ImageView status_prev3_play; + ImageView status_prev4_play; + RelativeLayout status_prev4_container; + ImageView status_reply; + ImageView status_pin; + ImageView status_privacy; + FloatingActionButton status_translate; + LinearLayout status_container2; + LinearLayout status_container3; + LinearLayout main_container; + TextView yandex_translate; + TextView google_translate; + LinearLayout status_action_container; + LinearLayout status_replies; + LinearLayout status_replies_profile_pictures; + TextView status_replies_text; + LinearLayout loader_replies; + + ImageView new_element; + + ViewHolder(View itemView) { + super(itemView); + loader_replies = itemView.findViewById(R.id.loader_replies); + card_status_container = itemView.findViewById(R.id.card_status_container); + status_document_container = (LinearLayout) itemView.findViewById(R.id.status_document_container); + status_content = (TextView) itemView.findViewById(R.id.status_content); + status_content_translated = (TextView) itemView.findViewById(R.id.status_content_translated); + status_account_username = (TextView) itemView.findViewById(R.id.status_account_username); + status_account_displayname = (TextView) itemView.findViewById(R.id.status_account_displayname); + status_account_profile = (ImageView) itemView.findViewById(R.id.status_account_profile); + status_account_profile_boost = (ImageView) itemView.findViewById(R.id.status_account_profile_boost); + status_account_profile_boost_by = (ImageView) itemView.findViewById(R.id.status_account_profile_boost_by); + status_favorite_count = (TextView) itemView.findViewById(R.id.status_favorite_count); + status_reblog_count = (TextView) itemView.findViewById(R.id.status_reblog_count); + status_pin = (ImageView) itemView.findViewById(R.id.status_pin); + status_toot_date = (TextView) itemView.findViewById(R.id.status_toot_date); + status_show_more = (Button) itemView.findViewById(R.id.status_show_more); + status_more = (ImageView) itemView.findViewById(R.id.status_more); + status_reblog_user = (TextView) itemView.findViewById(R.id.status_reblog_user); + status_prev1 = (ImageView) itemView.findViewById(R.id.status_prev1); + status_prev2 = (ImageView) itemView.findViewById(R.id.status_prev2); + status_prev3 = (ImageView) itemView.findViewById(R.id.status_prev3); + status_prev4 = (ImageView) itemView.findViewById(R.id.status_prev4); + status_prev1_play = (ImageView) itemView.findViewById(R.id.status_prev1_play); + status_prev2_play = (ImageView) itemView.findViewById(R.id.status_prev2_play); + status_prev3_play = (ImageView) itemView.findViewById(R.id.status_prev3_play); + status_prev4_play = (ImageView) itemView.findViewById(R.id.status_prev4_play); + status_container2 = (LinearLayout) itemView.findViewById(R.id.status_container2); + status_container3 = (LinearLayout) itemView.findViewById(R.id.status_container3); + status_prev4_container = (RelativeLayout) itemView.findViewById(R.id.status_prev4_container); + status_reply = (ImageView) itemView.findViewById(R.id.status_reply); + status_privacy = (ImageView) itemView.findViewById(R.id.status_privacy); + status_translate = (FloatingActionButton) itemView.findViewById(R.id.status_translate); + status_content_translated_container = (LinearLayout) itemView.findViewById(R.id.status_content_translated_container); + main_container = (LinearLayout) itemView.findViewById(R.id.main_container); + status_spoiler_container = (LinearLayout) itemView.findViewById(R.id.status_spoiler_container); + status_content_container = (LinearLayout) itemView.findViewById(R.id.status_content_container); + status_spoiler = (TextView) itemView.findViewById(R.id.status_spoiler); + status_spoiler_button = (Button) itemView.findViewById(R.id.status_spoiler_button); + yandex_translate = (TextView) itemView.findViewById(R.id.yandex_translate); + google_translate = (TextView) itemView.findViewById(R.id.google_translate); + status_replies = (LinearLayout) itemView.findViewById(R.id.status_replies); + status_replies_profile_pictures = (LinearLayout) itemView.findViewById(R.id.status_replies_profile_pictures); + status_replies_text = (TextView) itemView.findViewById(R.id.status_replies_text); + new_element = (ImageView) itemView.findViewById(R.id.new_element); + status_action_container = (LinearLayout) itemView.findViewById(R.id.status_action_container); + + } } @Override @@ -175,13 +268,23 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf return DISPLAYED_STATUS; } } + @Override + public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { + if( viewType == DISPLAYED_STATUS) + return new ViewHolder(layoutInflater.inflate(R.layout.drawer_status, parent, false)); + else + return new ViewHolderEmpty(layoutInflater.inflate(R.layout.drawer_status, parent, false)); + } + @Override - public View getView(final int position, View convertView, ViewGroup parent) { + public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) { + + if( viewHolder.getItemViewType() == HIDDEN_STATUS){ - if( getItemViewType(position) == HIDDEN_STATUS){ - return new View(context); }else { + final ViewHolder holder = (ViewHolder) viewHolder; + holder.card_status_container.setVisibility(View.VISIBLE); final Status status = statuses.get(position); imageLoader = ImageLoader.getInstance(); File cacheDir = new File(context.getCacheDir(), context.getString(R.string.app_name)); @@ -197,57 +300,6 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf options = new DisplayImageOptions.Builder().displayer(new SimpleBitmapDisplayer()).cacheInMemory(false) .cacheOnDisk(true).resetViewBeforeLoading(true).build(); - if (convertView == null) { - convertView = layoutInflater.inflate(R.layout.drawer_status, parent, false); - holder = new ViewHolder(); - holder.loader_replies = (LinearLayout) convertView.findViewById(R.id.loader_replies); - holder.card_status_container = (CardView) convertView.findViewById(R.id.card_status_container); - holder.status_document_container = (LinearLayout) convertView.findViewById(R.id.status_document_container); - holder.status_content = (TextView) convertView.findViewById(R.id.status_content); - holder.status_content_translated = (TextView) convertView.findViewById(R.id.status_content_translated); - holder.status_account_username = (TextView) convertView.findViewById(R.id.status_account_username); - holder.status_account_displayname = (TextView) convertView.findViewById(R.id.status_account_displayname); - holder.status_account_profile = (ImageView) convertView.findViewById(R.id.status_account_profile); - holder.status_account_profile_boost = (ImageView) convertView.findViewById(R.id.status_account_profile_boost); - holder.status_account_profile_boost_by = (ImageView) convertView.findViewById(R.id.status_account_profile_boost_by); - holder.status_favorite_count = (TextView) convertView.findViewById(R.id.status_favorite_count); - holder.status_reblog_count = (TextView) convertView.findViewById(R.id.status_reblog_count); - holder.status_pin = (ImageView) convertView.findViewById(R.id.status_pin); - holder.status_toot_date = (TextView) convertView.findViewById(R.id.status_toot_date); - holder.status_show_more = (Button) convertView.findViewById(R.id.status_show_more); - holder.status_more = (ImageView) convertView.findViewById(R.id.status_more); - holder.status_reblog_user = (TextView) convertView.findViewById(R.id.status_reblog_user); - holder.status_prev1 = (ImageView) convertView.findViewById(R.id.status_prev1); - holder.status_prev2 = (ImageView) convertView.findViewById(R.id.status_prev2); - holder.status_prev3 = (ImageView) convertView.findViewById(R.id.status_prev3); - holder.status_prev4 = (ImageView) convertView.findViewById(R.id.status_prev4); - holder.status_prev1_play = (ImageView) convertView.findViewById(R.id.status_prev1_play); - holder.status_prev2_play = (ImageView) convertView.findViewById(R.id.status_prev2_play); - holder.status_prev3_play = (ImageView) convertView.findViewById(R.id.status_prev3_play); - holder.status_prev4_play = (ImageView) convertView.findViewById(R.id.status_prev4_play); - holder.status_container2 = (LinearLayout) convertView.findViewById(R.id.status_container2); - holder.status_container3 = (LinearLayout) convertView.findViewById(R.id.status_container3); - holder.status_prev4_container = (RelativeLayout) convertView.findViewById(R.id.status_prev4_container); - holder.status_reply = (ImageView) convertView.findViewById(R.id.status_reply); - holder.status_privacy = (ImageView) convertView.findViewById(R.id.status_privacy); - holder.status_translate = (FloatingActionButton) convertView.findViewById(R.id.status_translate); - holder.status_content_translated_container = (LinearLayout) convertView.findViewById(R.id.status_content_translated_container); - holder.main_container = (LinearLayout) convertView.findViewById(R.id.main_container); - holder.status_spoiler_container = (LinearLayout) convertView.findViewById(R.id.status_spoiler_container); - holder.status_content_container = (LinearLayout) convertView.findViewById(R.id.status_content_container); - holder.status_spoiler = (TextView) convertView.findViewById(R.id.status_spoiler); - holder.status_spoiler_button = (Button) convertView.findViewById(R.id.status_spoiler_button); - holder.yandex_translate = (TextView) convertView.findViewById(R.id.yandex_translate); - holder.google_translate = (TextView) convertView.findViewById(R.id.google_translate); - holder.status_replies = (LinearLayout) convertView.findViewById(R.id.status_replies); - holder.status_replies_profile_pictures = (LinearLayout) convertView.findViewById(R.id.status_replies_profile_pictures); - holder.status_replies_text = (TextView) convertView.findViewById(R.id.status_replies_text); - holder.new_element = (ImageView) convertView.findViewById(R.id.new_element); - holder.status_action_container = (LinearLayout) convertView.findViewById(R.id.status_action_container); - convertView.setTag(holder); - } else { - holder = (ViewHolder) convertView.getTag(); - } final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -902,7 +954,6 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf - final View finalConvertView = convertView; final View attached = holder.status_more; holder.status_more.setOnClickListener(new View.OnClickListener() { @Override @@ -986,7 +1037,7 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf @Override public void run() { - Bitmap bitmap = Helper.convertTootIntoBitmap(context, finalConvertView); + Bitmap bitmap = Helper.convertTootIntoBitmap(context, holder.card_status_container); status.setTakingScreenShot(false); statusListAdapter.notifyDataSetChanged(); Intent intent = new Intent(context, TootActivity.class); @@ -1086,14 +1137,17 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf } } }); - return convertView; } - } - private void loadAttachments(final Status status, ViewHolder holder){ + + + + + private void loadAttachments(final Status status, RecyclerView.ViewHolder viewHolder){ + final ViewHolder holder = (ViewHolder) viewHolder; List attachments = status.getMedia_attachments(); if( attachments != null && attachments.size() > 0){ int i = 0; @@ -1379,53 +1433,7 @@ public class StatusListAdapter extends BaseAdapter implements OnPostActionInterf } - private class ViewHolder { - LinearLayout status_content_container; - LinearLayout status_spoiler_container; - TextView status_spoiler; - Button status_spoiler_button; - CardView card_status_container; - TextView status_content; - TextView status_content_translated; - LinearLayout status_content_translated_container; - TextView status_account_username; - TextView status_account_displayname; - ImageView status_account_profile; - ImageView status_account_profile_boost; - ImageView status_account_profile_boost_by; - TextView status_favorite_count; - TextView status_reblog_count; - TextView status_toot_date; - TextView status_reblog_user; - Button status_show_more; - ImageView status_more; - LinearLayout status_document_container; - ImageView status_prev1; - ImageView status_prev2; - ImageView status_prev3; - ImageView status_prev4; - ImageView status_prev1_play; - ImageView status_prev2_play; - ImageView status_prev3_play; - ImageView status_prev4_play; - RelativeLayout status_prev4_container; - ImageView status_reply; - ImageView status_pin; - ImageView status_privacy; - FloatingActionButton status_translate; - LinearLayout status_container2; - LinearLayout status_container3; - LinearLayout main_container; - TextView yandex_translate; - TextView google_translate; - LinearLayout status_action_container; - LinearLayout status_replies; - LinearLayout status_replies_profile_pictures; - TextView status_replies_text; - LinearLayout loader_replies; - ImageView new_element; - } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java index 215db5a59..09406ac96 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java @@ -25,6 +25,8 @@ import android.support.v4.app.Fragment; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.ViewCompat; import android.support.v4.widget.SwipeRefreshLayout; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; @@ -75,7 +77,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn private String targetedId; private String tag; private boolean swiped; - private ListView lv_status; + private RecyclerView lv_status; private boolean isOnWifi; private int behaviorWithAttachments; private boolean showMediaOnly, showPinned; @@ -128,7 +130,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); if( type == RetrieveFeedsAsyncTask.Type.HOME) lastReadStatus = sharedpreferences.getString(Helper.LAST_HOMETIMELINE_MAX_ID + userId, null); - lv_status = (ListView) rootView.findViewById(R.id.lv_status); + lv_status = (RecyclerView) rootView.findViewById(R.id.lv_status); mainLoader = (RelativeLayout) rootView.findViewById(R.id.loader); nextElementLoader = (RelativeLayout) rootView.findViewById(R.id.loading_next_status); textviewNoAction = (RelativeLayout) rootView.findViewById(R.id.no_action); @@ -142,47 +144,34 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn if (hideHeader && Build.VERSION.SDK_INT >= 21) ViewCompat.setNestedScrollingEnabled(lv_status, true); - lv_status.setOnScrollListener(new AbsListView.OnScrollListener() { - int lastFirstVisibleItem = 0; - @Override - public void onScrollStateChanged(AbsListView view, int scrollState) { + final LinearLayoutManager mLayoutManager; + mLayoutManager = new LinearLayoutManager(context); + lv_status.setLayoutManager(mLayoutManager); - } - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if (hideHeader && Build.VERSION.SDK_INT < 21) { - if(firstVisibleItem == 0 && Helper.listIsAtTop(lv_status)){ - Intent intent = new Intent(Helper.HEADER_ACCOUNT+instanceValue); - intent.putExtra("hide", false); - LocalBroadcastManager.getInstance(context).sendBroadcast(intent); - }else if (view.getId() == lv_status.getId() && totalItemCount > visibleItemCount) { - final int currentFirstVisibleItem = lv_status.getFirstVisiblePosition(); - if (currentFirstVisibleItem > lastFirstVisibleItem) { - Intent intent = new Intent(Helper.HEADER_ACCOUNT + instanceValue); - intent.putExtra("hide", true); - LocalBroadcastManager.getInstance(context).sendBroadcast(intent); - } else if (currentFirstVisibleItem < lastFirstVisibleItem) { - Intent intent = new Intent(Helper.HEADER_ACCOUNT + instanceValue); - intent.putExtra("hide", false); - LocalBroadcastManager.getInstance(context).sendBroadcast(intent); + lv_status.addOnScrollListener(new RecyclerView.OnScrollListener() { + public void onScrolled(RecyclerView recyclerView, int dx, int dy) + { + if(dy > 0){ + int visibleItemCount = mLayoutManager.getChildCount(); + int totalItemCount = mLayoutManager.getItemCount(); + int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); + if(firstVisibleItem + visibleItemCount == totalItemCount ) { + if(!flag_loading ) { + flag_loading = true; + if( type == RetrieveFeedsAsyncTask.Type.USER) + asyncTask = new RetrieveFeedsAsyncTask(context, type, targetedId, max_id, showMediaOnly, showPinned, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + else if( type == RetrieveFeedsAsyncTask.Type.TAG) + asyncTask = new RetrieveFeedsAsyncTask(context, type, tag, targetedId, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + else + asyncTask = new RetrieveFeedsAsyncTask(context, type, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + + nextElementLoader.setVisibility(View.VISIBLE); } - lastFirstVisibleItem = currentFirstVisibleItem; + } else { + nextElementLoader.setVisibility(View.GONE); } } - if(firstVisibleItem + visibleItemCount == totalItemCount ) { - if(!flag_loading ) { - flag_loading = true; - if( type == RetrieveFeedsAsyncTask.Type.USER) - asyncTask = new RetrieveFeedsAsyncTask(context, type, targetedId, max_id, showMediaOnly, showPinned, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - else if( type == RetrieveFeedsAsyncTask.Type.TAG) - asyncTask = new RetrieveFeedsAsyncTask(context, type, tag, targetedId, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - else - asyncTask = new RetrieveFeedsAsyncTask(context, type, max_id, DisplayStatusFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - nextElementLoader.setVisibility(View.VISIBLE); - } - } else { - nextElementLoader.setVisibility(View.GONE); - } } }); @@ -336,9 +325,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn if (status != null) { //Update the id of the last toot retrieved MainActivity.lastHomeId = status.getId(); - int index = lv_status.getFirstVisiblePosition() + 1; - View v = lv_status.getChildAt(0); - int top = (v == null) ? 0 : v.getTop(); status.setReplies(new ArrayList()); statuses.add(0,status); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -346,7 +332,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn if( !status.getAccount().getId().equals(userId)) MainActivity.countNewStatus++; statusListAdapter.notifyDataSetChanged(); - lv_status.setSelectionFromTop(index, top); if (textviewNoAction.getVisibility() == View.VISIBLE) textviewNoAction.setVisibility(View.GONE); } @@ -355,15 +340,8 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn return; //Avoids the array to be too big... if (status != null) { - if (lv_status.getFirstVisiblePosition() == 0) { - status.setReplies(new ArrayList()); - status.setNew(false); - statuses.add(0, status); - statusListAdapter.notifyDataSetChanged(); - } else { - status.setReplies(new ArrayList()); - statuses.add(0, status); - } + status.setReplies(new ArrayList()); + statuses.add(0, status); if (textviewNoAction.getVisibility() == View.VISIBLE) textviewNoAction.setVisibility(View.GONE); } @@ -374,11 +352,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn * Refresh status in list */ public void refreshFilter(){ - int index = lv_status.getFirstVisiblePosition() + 1; - View v = lv_status.getChildAt(0); - int top = (v == null) ? 0 : v.getTop(); statusListAdapter.notifyDataSetChanged(); - lv_status.setSelectionFromTop(index, top); } @Override @@ -543,39 +517,19 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn for (Status st : this.statuses) { knownId.add(st.getId()); } - if( lv_status.getFirstVisiblePosition() > 1 ) { - int index = lv_status.getFirstVisiblePosition() + statuses.size(); - View v = lv_status.getChildAt(0); - int top = (v == null) ? 0 : v.getTop(); - for (int i = statuses.size() - 1; i >= 0; i--) { - if (!knownId.contains(statuses.get(i).getId())) { - if (type == RetrieveFeedsAsyncTask.Type.HOME) - statuses.get(i).setNew(true); - statuses.get(i).setReplies(new ArrayList()); - this.statuses.add(0, statuses.get(i)); - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - if (type == RetrieveFeedsAsyncTask.Type.HOME && !statuses.get(i).getAccount().getId().equals(userId)) - MainActivity.countNewStatus++; - } + for (int i = statuses.size() - 1; i >= 0; i--) { + if (!knownId.contains(statuses.get(i).getId())) { + if (type == RetrieveFeedsAsyncTask.Type.HOME) + statuses.get(i).setNew(true); + statuses.get(i).setReplies(new ArrayList()); + this.statuses.add(0, statuses.get(i)); + SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); + if (type == RetrieveFeedsAsyncTask.Type.HOME && !statuses.get(i).getAccount().getId().equals(userId)) + MainActivity.countNewStatus++; } - statusListAdapter.notifyDataSetChanged(); - lv_status.setSelectionFromTop(index, top); - }else { - for (int i = statuses.size() - 1; i >= 0; i--) { - if (!knownId.contains(statuses.get(i).getId())) { - if (type == RetrieveFeedsAsyncTask.Type.HOME) - statuses.get(i).setNew(true); - statuses.get(i).setReplies(new ArrayList()); - this.statuses.add(0, statuses.get(i)); - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - if (type == RetrieveFeedsAsyncTask.Type.HOME && !statuses.get(i).getAccount().getId().equals(userId)) - MainActivity.countNewStatus++; - } - } - statusListAdapter.notifyDataSetChanged(); } + statusListAdapter.notifyDataSetChanged(); try { ((MainActivity) context).updateHomeCounter(); }catch (Exception ignored){} diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/helper/CrossActions.java b/app/src/main/java/fr/gouv/etalab/mastodon/helper/CrossActions.java index 7acbad4f5..2cc0fd40e 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/helper/CrossActions.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/helper/CrossActions.java @@ -24,6 +24,7 @@ import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AlertDialog; +import android.support.v7.widget.RecyclerView; import android.text.Html; import android.util.Log; import android.widget.BaseAdapter; @@ -117,67 +118,6 @@ public class CrossActions { } } - public static void doCrossReply(final Context context, final Status status, final RetrieveFeedsAsyncTask.Type type, boolean limitedToOwner){ - List accounts = connectedAccounts(context, status, limitedToOwner); - - if( accounts.size() == 1) { - Intent intent = new Intent(context, TootActivity.class); - Bundle b = new Bundle(); - if( status.getReblog() != null ) - b.putParcelable("tootReply", status.getReblog()); - else - b.putParcelable("tootReply", status); - intent.putExtras(b); //Put your id to your next Intent - context.startActivity(intent); - if( type == RetrieveFeedsAsyncTask.Type.CONTEXT ){ - try { - //Avoid to open multi activities when replying in a conversation - ((ShowConversationActivity)context).finish(); - }catch (Exception ignored){} - - } - }else { - AlertDialog.Builder builderSingle = new AlertDialog.Builder(context); - builderSingle.setTitle(context.getString(R.string.choose_accounts)); - final AccountsSearchAdapter accountsSearchAdapter = new AccountsSearchAdapter(context, accounts, true); - final Account[] accountArray = new Account[accounts.size()]; - int i = 0; - for(Account account: accounts){ - accountArray[i] = account; - i++; - } - builderSingle.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }); - builderSingle.setAdapter(accountsSearchAdapter, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - Account account = accountArray[which]; - Intent intent = new Intent(context, TootActivity.class); - Bundle b = new Bundle(); - if( status.getReblog() != null ) - b.putParcelable("tootReply", status.getReblog()); - else - b.putParcelable("tootReply", status); - b.putParcelable("accountReply", account); - intent.putExtras(b); //Put your id to your next Intent - context.startActivity(intent); - if( type == RetrieveFeedsAsyncTask.Type.CONTEXT ){ - try { - //Avoid to open multi activities when replying in a conversation - ((ShowConversationActivity)context).finish(); - }catch (Exception ignored){} - - } - dialog.dismiss(); - } - }); - builderSingle.show(); - } - } /** @@ -335,4 +275,256 @@ public class CrossActions { } + + + + + + + + + + + + + + + + + + + public static void doCrossAction(final Context context, final Status status, final API.StatusAction doAction, final RecyclerView.Adapter baseAdapter, final OnPostActionInterface onPostActionInterface, boolean limitedToOwner){ + List accounts = connectedAccounts(context, status, limitedToOwner); + final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); + + boolean undoAction = (doAction == API.StatusAction.UNPIN || doAction == API.StatusAction.UNREBLOG || doAction == API.StatusAction.UNFAVOURITE ); + //Undo actions won't ask for choosing a user + if( accounts.size() == 1 || undoAction ) { + + boolean confirmation = false; + if( doAction == API.StatusAction.UNFAVOURITE || doAction == API.StatusAction.FAVOURITE) + confirmation = sharedpreferences.getBoolean(Helper.SET_NOTIF_VALIDATION_FAV, false); + else if( doAction == API.StatusAction.UNREBLOG || doAction == API.StatusAction.REBLOG ) + confirmation = sharedpreferences.getBoolean(Helper.SET_NOTIF_VALIDATION, true); + if (confirmation) + displayConfirmationDialog(context, doAction, status, baseAdapter, onPostActionInterface); + else { + if( doAction == API.StatusAction.REBLOG || doAction == API.StatusAction.UNREBLOG) + reblogAction(context, status, baseAdapter, onPostActionInterface); + else if( doAction == API.StatusAction.FAVOURITE || doAction == API.StatusAction.UNFAVOURITE) + favouriteAction(context, status, baseAdapter, onPostActionInterface); + else if ( doAction == API.StatusAction.PIN || doAction == API.StatusAction.UNPIN) + pinAction(context, status, baseAdapter, onPostActionInterface); + } + }else { + AlertDialog.Builder builderSingle = new AlertDialog.Builder(context); + builderSingle.setTitle(context.getString(R.string.choose_accounts)); + final AccountsSearchAdapter accountsSearchAdapter = new AccountsSearchAdapter(context, accounts, true); + final Account[] accountArray = new Account[accounts.size()]; + int i = 0; + for(Account account: accounts){ + accountArray[i] = account; + i++; + } + builderSingle.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); + builderSingle.setAdapter(accountsSearchAdapter, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + Account selectedAccount = accountArray[which]; + String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); + SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); + Account loggedAccount = new AccountDAO(context, db).getAccountByID(userId); + if(loggedAccount.getInstance().equals(selectedAccount.getInstance())){ + new PostActionAsyncTask(context, selectedAccount, doAction, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + }else{ //Account is from another instance + new PostActionAsyncTask(context, selectedAccount, status, doAction, onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } + if( selectedAccount.getInstance().equals(loggedAccount.getInstance()) && selectedAccount.getId().equals(loggedAccount.getId())) { + if (doAction == API.StatusAction.REBLOG) { + status.setReblogged(true); + } else if (doAction == API.StatusAction.FAVOURITE) { + status.setFavourited(true); + } else if (doAction == API.StatusAction.PIN) { + status.setPinned(true); + } + baseAdapter.notifyDataSetChanged(); + } + dialog.dismiss(); + } + }); + builderSingle.show(); + } + } + + public static void doCrossReply(final Context context, final Status status, final RetrieveFeedsAsyncTask.Type type, boolean limitedToOwner){ + List accounts = connectedAccounts(context, status, limitedToOwner); + + if( accounts.size() == 1) { + Intent intent = new Intent(context, TootActivity.class); + Bundle b = new Bundle(); + if( status.getReblog() != null ) + b.putParcelable("tootReply", status.getReblog()); + else + b.putParcelable("tootReply", status); + intent.putExtras(b); //Put your id to your next Intent + context.startActivity(intent); + if( type == RetrieveFeedsAsyncTask.Type.CONTEXT ){ + try { + //Avoid to open multi activities when replying in a conversation + ((ShowConversationActivity)context).finish(); + }catch (Exception ignored){} + + } + }else { + AlertDialog.Builder builderSingle = new AlertDialog.Builder(context); + builderSingle.setTitle(context.getString(R.string.choose_accounts)); + final AccountsSearchAdapter accountsSearchAdapter = new AccountsSearchAdapter(context, accounts, true); + final Account[] accountArray = new Account[accounts.size()]; + int i = 0; + for(Account account: accounts){ + accountArray[i] = account; + i++; + } + builderSingle.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); + builderSingle.setAdapter(accountsSearchAdapter, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + Account account = accountArray[which]; + Intent intent = new Intent(context, TootActivity.class); + Bundle b = new Bundle(); + if( status.getReblog() != null ) + b.putParcelable("tootReply", status.getReblog()); + else + b.putParcelable("tootReply", status); + b.putParcelable("accountReply", account); + intent.putExtras(b); //Put your id to your next Intent + context.startActivity(intent); + if( type == RetrieveFeedsAsyncTask.Type.CONTEXT ){ + try { + //Avoid to open multi activities when replying in a conversation + ((ShowConversationActivity)context).finish(); + }catch (Exception ignored){} + + } + dialog.dismiss(); + } + }); + builderSingle.show(); + } + } + + + /** + * Display a validation message + * @param action int + * @param status Status + */ + private static void displayConfirmationDialog(final Context context, final API.StatusAction action, final Status status, final RecyclerView.Adapter baseAdapter, final OnPostActionInterface onPostActionInterface){ + + String title = null; + if( action == API.StatusAction.FAVOURITE){ + title = context.getString(R.string.favourite_add); + }else if( action == API.StatusAction.UNFAVOURITE){ + title = context.getString(R.string.favourite_remove); + }else if( action == API.StatusAction.REBLOG){ + title = context.getString(R.string.reblog_add); + }else if(action == API.StatusAction.UNREBLOG){ + title = context.getString(R.string.reblog_remove); + }else if ( action == API.StatusAction.PIN) { + title = context.getString(R.string.pin_add); + }else if (action == API.StatusAction.UNPIN) { + title = context.getString(R.string.pin_remove); + } + + AlertDialog.Builder builder = new AlertDialog.Builder(context); + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) + builder.setMessage(Html.fromHtml(status.getContent(), Html.FROM_HTML_MODE_LEGACY)); + else + //noinspection deprecation + builder.setMessage(Html.fromHtml(status.getContent())); + builder.setIcon(android.R.drawable.ic_dialog_alert) + .setTitle(title) + .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + if( action == API.StatusAction.REBLOG || action == API.StatusAction.UNREBLOG) + reblogAction(context, status, baseAdapter, onPostActionInterface); + else if( action == API.StatusAction.FAVOURITE || action == API.StatusAction.UNFAVOURITE) + favouriteAction(context, status, baseAdapter, onPostActionInterface); + else if ( action == API.StatusAction.PIN || action == API.StatusAction.UNPIN) + pinAction(context, status, baseAdapter, onPostActionInterface); + dialog.dismiss(); + } + }) + .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + + }) + .show(); + } + + /** + * Favourites/Unfavourites a status + * @param status Status + */ + private static void favouriteAction(Context context, Status status, RecyclerView.Adapter baseAdapter, OnPostActionInterface onPostActionInterface){ + if( status.isFavourited() || (status.getReblog() != null && status.getReblog().isFavourited())){ + new PostActionAsyncTask(context, API.StatusAction.UNFAVOURITE, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + status.setFavourited(false); + }else{ + new PostActionAsyncTask(context, API.StatusAction.FAVOURITE, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + status.setFavourited(true); + } + baseAdapter.notifyDataSetChanged(); + } + + /** + * Reblog/Unreblog a status + * @param status Status + */ + private static void reblogAction(Context context, Status status, RecyclerView.Adapter baseAdapter, OnPostActionInterface onPostActionInterface){ + if( status.isReblogged() || (status.getReblog()!= null && status.getReblog().isReblogged())){ + String statusId = status.getReblog()!=null?status.getReblog().getId():status.getId(); + new PostActionAsyncTask(context, API.StatusAction.UNREBLOG, statusId, onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + status.setReblogged(false); + }else{ + new PostActionAsyncTask(context, API.StatusAction.REBLOG, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + status.setReblogged(true); + } + baseAdapter.notifyDataSetChanged(); + } + + /** + * Pin or unpin a status + * @param status Status + */ + private static void pinAction(Context context, Status status, RecyclerView.Adapter baseAdapter, OnPostActionInterface onPostActionInterface) { + + if (status.isPinned()) { + new PostActionAsyncTask(context, API.StatusAction.UNPIN, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + status.setPinned(false); + } else { + new PostActionAsyncTask(context, API.StatusAction.PIN, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + status.setPinned(true); + } + baseAdapter.notifyDataSetChanged(); + } + + + + } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java b/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java index 6431b3b9d..977fd9583 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java @@ -58,6 +58,7 @@ import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; +import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.Html; import android.text.SpannableString; @@ -1527,6 +1528,15 @@ public class Helper { } } + /** + * Returns true if a ListView is at its top position + * @param listView ListView + * @return boolean + */ + public static boolean listIsAtTop(RecyclerView listView) { + return listView.getChildCount() == 0 || listView.getChildAt(0).getTop() == 0; + } + /** * Returns true if a ListView is at its top position * @param listView ListView diff --git a/app/src/main/res/layout/fragment_accounts.xml b/app/src/main/res/layout/fragment_accounts.xml index 977406ff7..53f206078 100644 --- a/app/src/main/res/layout/fragment_accounts.xml +++ b/app/src/main/res/layout/fragment_accounts.xml @@ -27,14 +27,13 @@ android:layout_width="match_parent" android:id="@+id/swipeContainer" android:layout_height="match_parent"> - - + /> - Date: Mon, 23 Oct 2017 07:19:28 +0200 Subject: [PATCH 02/46] Create LICENSE --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 674 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..481361030 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + Mastalab is a Mastodon client for Android devices + Copyright (C) 2017 Thomas Schneider + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Mastalab Copyright (C) 2017 Thomas Schneider + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. From ace213df6e9dbef9807762028d567737902c22bb Mon Sep 17 00:00:00 2001 From: stom79 Date: Tue, 24 Oct 2017 10:11:07 +0200 Subject: [PATCH 03/46] Starting two actionbars --- .../mastodon/activities/BaseMainActivity.java | 2 ++ app/src/main/res/layout/activity_main.xml | 15 ++++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java index fb043bd3e..b12a3e71f 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java @@ -179,7 +179,9 @@ public abstract class BaseMainActivity extends AppCompatActivity Helper.fillMapEmoji(getApplicationContext()); //Here, the user is authenticated Toolbar toolbar = findViewById(R.id.toolbar); + Toolbar toolbarBottom = findViewById(R.id.toolbarBottom); setSupportActionBar(toolbar); + setSupportActionBar(toolbarBottom); toolbarTitle = toolbar.findViewById(R.id.toolbar_title); toolbar_search = toolbar.findViewById(R.id.toolbar_search); tabLayout = findViewById(R.id.tabLayout); diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index ca2d396de..60c69ba1a 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -32,6 +32,7 @@ @@ -107,10 +108,18 @@ android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" - tools:context="mastodon.etalab.gouv.fr.mastodon.fr.etalab.gouv.fr.mastodon.activities.MainActivity" + tools:context="fr.gouv.etalab.mastodon.activities.MainActivity" > - + Date: Tue, 24 Oct 2017 11:03:36 +0200 Subject: [PATCH 04/46] Starting two actionbars --- .../mastodon/drawers/StatusListAdapter.java | 9 +-- .../fragments/DisplayStatusFragment.java | 74 ++++--------------- app/src/main/res/layout/activity_main.xml | 4 +- 3 files changed, 19 insertions(+), 68 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java index 14cbbc55e..3018257d3 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java @@ -193,7 +193,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct TextView status_favorite_count; TextView status_reblog_count; TextView status_toot_date; - TextView status_reblog_user; Button status_show_more; ImageView status_more; LinearLayout status_document_container; @@ -241,7 +240,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct status_toot_date = (TextView) itemView.findViewById(R.id.status_toot_date); status_show_more = (Button) itemView.findViewById(R.id.status_show_more); status_more = (ImageView) itemView.findViewById(R.id.status_more); - status_reblog_user = (TextView) itemView.findViewById(R.id.status_reblog_user); status_prev1 = (ImageView) itemView.findViewById(R.id.status_prev1); status_prev2 = (ImageView) itemView.findViewById(R.id.status_prev2); status_prev3 = (ImageView) itemView.findViewById(R.id.status_prev3); @@ -480,9 +478,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct content = status.getReblog().getContent(); displayName = Helper.shortnameToUnicode(status.getReblog().getAccount().getDisplay_name(), true); username = status.getReblog().getAccount().getUsername(); - holder.status_reblog_user.setText(displayName + " " +String.format("@%s",username)); + holder.status_account_displayname.setText(displayName + " " +String.format("@%s",username)); ppurl = status.getReblog().getAccount().getAvatar(); - holder.status_reblog_user.setVisibility(View.VISIBLE); + holder.status_account_displayname.setVisibility(View.VISIBLE); holder.status_account_displayname.setText(context.getResources().getString(R.string.reblog_by, status.getAccount().getUsername())); name = String.format("%s @%s",displayName,status.getReblog().getAccount().getAcct()); }else { @@ -1014,7 +1012,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct - final View finalConvertView = convertView; final View attached = holder.status_more; holder.status_more.setOnClickListener(new View.OnClickListener() { @Override @@ -1098,7 +1095,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void run() { - Bitmap bitmap = Helper.convertTootIntoBitmap(context, finalConvertView); + Bitmap bitmap = Helper.convertTootIntoBitmap(context, holder.status_content_container); status.setTakingScreenShot(false); statusListAdapter.notifyDataSetChanged(); Intent intent = new Intent(context, TootActivity.class); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java index ff2f4eeb9..ce3262439 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java @@ -24,12 +24,9 @@ import android.support.v4.view.ViewCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; -import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.AbsListView; -import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Toast; import java.util.ArrayList; @@ -98,7 +95,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn type = (RetrieveFeedsAsyncTask.Type) bundle.get("type"); targetedId = bundle.getString("targetedId", null); tag = bundle.getString("tag", null); - instanceValue = bundle.getString("hideHeaderValue", null); hideHeader = bundle.getBoolean("hideHeader", false); showMediaOnly = bundle.getBoolean("showMediaOnly",false); showPinned = bundle.getBoolean("showPinned",false); @@ -317,9 +313,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn if (status != null && !knownId.contains(status.getId())) { //Update the id of the last toot retrieved MainActivity.lastHomeId = status.getId(); - int index = lv_status.getFirstVisiblePosition() + 1; - View v = lv_status.getChildAt(0); - int top = (v == null) ? 0 : v.getTop(); status.setReplies(new ArrayList()); statuses.add(0,status); knownId.add(0,status.getId()); @@ -328,7 +321,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn if( !status.getAccount().getId().equals(userId)) MainActivity.countNewStatus++; statusListAdapter.notifyDataSetChanged(); - lv_status.setSelectionFromTop(index, top); if (textviewNoAction.getVisibility() == View.VISIBLE) textviewNoAction.setVisibility(View.GONE); } @@ -338,17 +330,8 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn if (status != null && !knownId.contains(status.getId())) { status.setReplies(new ArrayList()); status.setNew(false); - if (lv_status.getFirstVisiblePosition() == 0) { - statuses.add(0, status); - statusListAdapter.notifyDataSetChanged(); - } else { - int index = lv_status.getFirstVisiblePosition() + 1; - View v = lv_status.getChildAt(0); - int top = (v == null) ? 0 : v.getTop(); - statuses.add(0, status); - statusListAdapter.notifyDataSetChanged(); - lv_status.setSelectionFromTop(index, top); - } + statuses.add(0, status); + statusListAdapter.notifyDataSetChanged(); knownId.add(0, status.getId()); if (textviewNoAction.getVisibility() == View.VISIBLE) textviewNoAction.setVisibility(View.GONE); @@ -360,11 +343,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn * Refresh status in list */ public void refreshFilter(){ - int index = lv_status.getFirstVisiblePosition() + 1; - View v = lv_status.getChildAt(0); - int top = (v == null) ? 0 : v.getTop(); statusListAdapter.notifyDataSetChanged(); - lv_status.setSelectionFromTop(index, top); } @Override @@ -397,11 +376,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn retrieveMissingToots(statuses.get(0).getId()); } } - int index = lv_status.getFirstVisiblePosition(); - View v = lv_status.getChildAt(0); - int top = (v == null) ? 0 : v.getTop(); statusListAdapter.notifyDataSetChanged(); - lv_status.setSelectionFromTop(index, top); } /** @@ -530,41 +505,20 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn @Override public void onRetrieveMissingFeeds(List statuses) { if( statuses != null && statuses.size() > 0) { - if( lv_status.getFirstVisiblePosition() > 1 ) { - int index = lv_status.getFirstVisiblePosition() + statuses.size(); - View v = lv_status.getChildAt(0); - int top = (v == null) ? 0 : v.getTop(); - for (int i = statuses.size() - 1; i >= 0; i--) { - if (!knownId.contains(statuses.get(i).getId())) { - if (type == RetrieveFeedsAsyncTask.Type.HOME) - statuses.get(i).setNew(true); - knownId.add(0, statuses.get(i).getId()); - statuses.get(i).setReplies(new ArrayList()); - this.statuses.add(0, statuses.get(i)); - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - if (type == RetrieveFeedsAsyncTask.Type.HOME && !statuses.get(i).getAccount().getId().equals(userId)) - MainActivity.countNewStatus++; - } + for (int i = statuses.size() - 1; i >= 0; i--) { + if (!knownId.contains(statuses.get(i).getId())) { + if (type == RetrieveFeedsAsyncTask.Type.HOME) + statuses.get(i).setNew(true); + knownId.add(0,statuses.get(i).getId()); + statuses.get(i).setReplies(new ArrayList()); + this.statuses.add(0, statuses.get(i)); + SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); + if (type == RetrieveFeedsAsyncTask.Type.HOME && !statuses.get(i).getAccount().getId().equals(userId)) + MainActivity.countNewStatus++; } - statusListAdapter.notifyDataSetChanged(); - lv_status.setSelectionFromTop(index, top); - }else { - for (int i = statuses.size() - 1; i >= 0; i--) { - if (!knownId.contains(statuses.get(i).getId())) { - if (type == RetrieveFeedsAsyncTask.Type.HOME) - statuses.get(i).setNew(true); - knownId.add(0,statuses.get(i).getId()); - statuses.get(i).setReplies(new ArrayList()); - this.statuses.add(0, statuses.get(i)); - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - if (type == RetrieveFeedsAsyncTask.Type.HOME && !statuses.get(i).getAccount().getId().equals(userId)) - MainActivity.countNewStatus++; - } - } - statusListAdapter.notifyDataSetChanged(); } + statusListAdapter.notifyDataSetChanged(); try { ((MainActivity) context).updateHomeCounter(); }catch (Exception ignored){} diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 60c69ba1a..78e4f4b4d 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -32,7 +32,6 @@ Date: Tue, 24 Oct 2017 11:29:56 +0200 Subject: [PATCH 05/46] Fixes issue with filter --- .../mastodon/drawers/StatusListAdapter.java | 92 +++++++++---------- app/src/main/res/layout/activity_hashtag.xml | 4 +- .../res/layout/activity_show_conversation.xml | 2 +- app/src/main/res/layout/drawer_empty.xml | 22 +++++ 4 files changed, 71 insertions(+), 49 deletions(-) create mode 100644 app/src/main/res/layout/drawer_empty.xml diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java index 3018257d3..29902f792 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java @@ -14,6 +14,7 @@ package fr.gouv.etalab.mastodon.drawers; * You should have received a copy of the GNU General Public License along with Mastalab; if not, * see . */ +import android.annotation.SuppressLint; import android.graphics.Bitmap; import android.graphics.Typeface; import android.os.Handler; @@ -48,7 +49,6 @@ import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; -import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; @@ -117,8 +117,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct private List statuses; private LayoutInflater layoutInflater; private ImageLoader imageLoader; - private DisplayImageOptions optionsAttachment; - private ViewHolder holder; private boolean isOnWifi; private int translator; private int behaviorWithAttachments; @@ -226,47 +224,47 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct super(itemView); loader_replies = itemView.findViewById(R.id.loader_replies); card_status_container = itemView.findViewById(R.id.card_status_container); - status_document_container = (LinearLayout) itemView.findViewById(R.id.status_document_container); - status_content = (TextView) itemView.findViewById(R.id.status_content); - status_content_translated = (TextView) itemView.findViewById(R.id.status_content_translated); - status_account_username = (TextView) itemView.findViewById(R.id.status_account_username); - status_account_displayname = (TextView) itemView.findViewById(R.id.status_account_displayname); - status_account_profile = (ImageView) itemView.findViewById(R.id.status_account_profile); - status_account_profile_boost = (ImageView) itemView.findViewById(R.id.status_account_profile_boost); - status_account_profile_boost_by = (ImageView) itemView.findViewById(R.id.status_account_profile_boost_by); - status_favorite_count = (TextView) itemView.findViewById(R.id.status_favorite_count); - status_reblog_count = (TextView) itemView.findViewById(R.id.status_reblog_count); - status_pin = (ImageView) itemView.findViewById(R.id.status_pin); - status_toot_date = (TextView) itemView.findViewById(R.id.status_toot_date); - status_show_more = (Button) itemView.findViewById(R.id.status_show_more); - status_more = (ImageView) itemView.findViewById(R.id.status_more); - status_prev1 = (ImageView) itemView.findViewById(R.id.status_prev1); - status_prev2 = (ImageView) itemView.findViewById(R.id.status_prev2); - status_prev3 = (ImageView) itemView.findViewById(R.id.status_prev3); - status_prev4 = (ImageView) itemView.findViewById(R.id.status_prev4); - status_prev1_play = (ImageView) itemView.findViewById(R.id.status_prev1_play); - status_prev2_play = (ImageView) itemView.findViewById(R.id.status_prev2_play); - status_prev3_play = (ImageView) itemView.findViewById(R.id.status_prev3_play); - status_prev4_play = (ImageView) itemView.findViewById(R.id.status_prev4_play); - status_container2 = (LinearLayout) itemView.findViewById(R.id.status_container2); - status_container3 = (LinearLayout) itemView.findViewById(R.id.status_container3); - status_prev4_container = (RelativeLayout) itemView.findViewById(R.id.status_prev4_container); - status_reply = (ImageView) itemView.findViewById(R.id.status_reply); - status_privacy = (ImageView) itemView.findViewById(R.id.status_privacy); - status_translate = (FloatingActionButton) itemView.findViewById(R.id.status_translate); - status_content_translated_container = (LinearLayout) itemView.findViewById(R.id.status_content_translated_container); - main_container = (LinearLayout) itemView.findViewById(R.id.main_container); - status_spoiler_container = (LinearLayout) itemView.findViewById(R.id.status_spoiler_container); - status_content_container = (LinearLayout) itemView.findViewById(R.id.status_content_container); - status_spoiler = (TextView) itemView.findViewById(R.id.status_spoiler); - status_spoiler_button = (Button) itemView.findViewById(R.id.status_spoiler_button); - yandex_translate = (TextView) itemView.findViewById(R.id.yandex_translate); - google_translate = (TextView) itemView.findViewById(R.id.google_translate); - status_replies = (LinearLayout) itemView.findViewById(R.id.status_replies); - status_replies_profile_pictures = (LinearLayout) itemView.findViewById(R.id.status_replies_profile_pictures); - status_replies_text = (TextView) itemView.findViewById(R.id.status_replies_text); - new_element = (ImageView) itemView.findViewById(R.id.new_element); - status_action_container = (LinearLayout) itemView.findViewById(R.id.status_action_container); + status_document_container = itemView.findViewById(R.id.status_document_container); + status_content = itemView.findViewById(R.id.status_content); + status_content_translated = itemView.findViewById(R.id.status_content_translated); + status_account_username = itemView.findViewById(R.id.status_account_username); + status_account_displayname = itemView.findViewById(R.id.status_account_displayname); + status_account_profile = itemView.findViewById(R.id.status_account_profile); + status_account_profile_boost = itemView.findViewById(R.id.status_account_profile_boost); + status_account_profile_boost_by = itemView.findViewById(R.id.status_account_profile_boost_by); + status_favorite_count = itemView.findViewById(R.id.status_favorite_count); + status_reblog_count = itemView.findViewById(R.id.status_reblog_count); + status_pin = itemView.findViewById(R.id.status_pin); + status_toot_date = itemView.findViewById(R.id.status_toot_date); + status_show_more = itemView.findViewById(R.id.status_show_more); + status_more = itemView.findViewById(R.id.status_more); + status_prev1 = itemView.findViewById(R.id.status_prev1); + status_prev2 = itemView.findViewById(R.id.status_prev2); + status_prev3 = itemView.findViewById(R.id.status_prev3); + status_prev4 = itemView.findViewById(R.id.status_prev4); + status_prev1_play = itemView.findViewById(R.id.status_prev1_play); + status_prev2_play = itemView.findViewById(R.id.status_prev2_play); + status_prev3_play = itemView.findViewById(R.id.status_prev3_play); + status_prev4_play = itemView.findViewById(R.id.status_prev4_play); + status_container2 = itemView.findViewById(R.id.status_container2); + status_container3 = itemView.findViewById(R.id.status_container3); + status_prev4_container = itemView.findViewById(R.id.status_prev4_container); + status_reply = itemView.findViewById(R.id.status_reply); + status_privacy = itemView.findViewById(R.id.status_privacy); + status_translate = itemView.findViewById(R.id.status_translate); + status_content_translated_container = itemView.findViewById(R.id.status_content_translated_container); + main_container = itemView.findViewById(R.id.main_container); + status_spoiler_container = itemView.findViewById(R.id.status_spoiler_container); + status_content_container = itemView.findViewById(R.id.status_content_container); + status_spoiler = itemView.findViewById(R.id.status_spoiler); + status_spoiler_button = itemView.findViewById(R.id.status_spoiler_button); + yandex_translate = itemView.findViewById(R.id.yandex_translate); + google_translate = itemView.findViewById(R.id.google_translate); + status_replies = itemView.findViewById(R.id.status_replies); + status_replies_profile_pictures = itemView.findViewById(R.id.status_replies_profile_pictures); + status_replies_text = itemView.findViewById(R.id.status_replies_text); + new_element = itemView.findViewById(R.id.new_element); + status_action_container = itemView.findViewById(R.id.status_action_container); } } @@ -292,12 +290,12 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct if( viewType == DISPLAYED_STATUS) return new ViewHolder(layoutInflater.inflate(R.layout.drawer_status, parent, false)); else - return new ViewHolderEmpty(layoutInflater.inflate(R.layout.drawer_status, parent, false)); + return new ViewHolderEmpty(layoutInflater.inflate(R.layout.drawer_empty, parent, false)); } @Override - public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, final int position) { + public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, @SuppressLint("RecyclerView") final int position) { if( viewHolder.getItemViewType() == HIDDEN_STATUS){ @@ -1262,6 +1260,8 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct url = attachment.getUrl(); else if( attachment.getType().equals("unknown")) url = attachment.getRemote_url(); + DisplayImageOptions optionsAttachment = new DisplayImageOptions.Builder().displayer(new SimpleBitmapDisplayer()).cacheInMemory(false) + .cacheOnDisk(true).resetViewBeforeLoading(true).build(); if( !url.trim().contains("missing.png")) imageLoader.displayImage(url, imageView, optionsAttachment); final int finalPosition = position; diff --git a/app/src/main/res/layout/activity_hashtag.xml b/app/src/main/res/layout/activity_hashtag.xml index 695e724bf..2c4cca427 100644 --- a/app/src/main/res/layout/activity_hashtag.xml +++ b/app/src/main/res/layout/activity_hashtag.xml @@ -27,14 +27,14 @@ android:layout_width="match_parent" android:id="@+id/swipeContainer" android:layout_height="match_parent"> - - + - + + + \ No newline at end of file From f809094efa45eafd5a4acd5e4c864c2db33f2f21 Mon Sep 17 00:00:00 2001 From: stom79 Date: Tue, 24 Oct 2017 11:38:58 +0200 Subject: [PATCH 06/46] Applies recycler view to accounts --- .../mastodon/drawers/AccountsListAdapter.java | 84 ++++++++----------- 1 file changed, 37 insertions(+), 47 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/AccountsListAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/AccountsListAdapter.java index f2523e58b..2fead447e 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/AccountsListAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/AccountsListAdapter.java @@ -21,12 +21,12 @@ import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; +import android.support.v7.widget.RecyclerView; import android.text.Html; import android.text.util.Linkify; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; @@ -55,7 +55,7 @@ import fr.gouv.etalab.mastodon.asynctasks.PostActionAsyncTask; * Created by Thomas on 27/04/2017. * Adapter for accounts */ -public class AccountsListAdapter extends BaseAdapter implements OnPostActionInterface { +public class AccountsListAdapter extends RecyclerView.Adapter implements OnPostActionInterface { private List accounts; private LayoutInflater layoutInflater; @@ -73,35 +73,18 @@ public class AccountsListAdapter extends BaseAdapter implements OnPostActionInte this.targetedId = targetedId; } - public enum action{ - FOLLOW, - UNFOLLOW, - UNBLOCK, - NOTHING, - UNMUTE - } - private API.StatusAction doAction; + + @Override - public int getCount() { - return accounts.size(); + public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { + return new ViewHolder(layoutInflater.inflate(R.layout.drawer_account, parent, false)); } @Override - public Object getItem(int position) { - return accounts.get(position); - } - - @Override - public long getItemId(int position) { - return position; - } - - - @Override - public View getView(final int position, View convertView, ViewGroup parent) { - + public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { + final AccountsListAdapter.ViewHolder holder = (AccountsListAdapter.ViewHolder) viewHolder; ImageLoader imageLoader = ImageLoader.getInstance(); File cacheDir = new File(context.getCacheDir(), context.getString(R.string.app_name)); ImageLoaderConfiguration configImg = new ImageLoaderConfiguration.Builder(context) @@ -116,26 +99,7 @@ public class AccountsListAdapter extends BaseAdapter implements OnPostActionInte DisplayImageOptions options = new DisplayImageOptions.Builder().displayer(new SimpleBitmapDisplayer()).cacheInMemory(false) .cacheOnDisk(true).resetViewBeforeLoading(true).build(); final Account account = accounts.get(position); - final ViewHolder holder; - if (convertView == null) { - convertView = layoutInflater.inflate(R.layout.drawer_account, parent, false); - holder = new ViewHolder(); - holder.account_pp = (ImageView) convertView.findViewById(R.id.account_pp); - holder.account_dn = (TextView) convertView.findViewById(R.id.account_dn); - holder.account_ac = (TextView) convertView.findViewById(R.id.account_ac); - holder.account_un = (TextView) convertView.findViewById(R.id.account_un); - holder.account_ds = (TextView) convertView.findViewById(R.id.account_ds); - holder.account_sc = (TextView) convertView.findViewById(R.id.account_sc); - holder.account_fgc = (TextView) convertView.findViewById(R.id.account_fgc); - holder.account_frc = (TextView) convertView.findViewById(R.id.account_frc); - holder.account_follow = (FloatingActionButton) convertView.findViewById(R.id.account_follow); - holder.account_follow_request = (TextView) convertView.findViewById(R.id.account_follow_request); - holder.account_container = (LinearLayout) convertView.findViewById(R.id.account_container); - convertView.setTag(holder); - } else { - holder = (ViewHolder) convertView.getTag(); - } if( action == RetrieveAccountsAsyncTask.Type.BLOCKED) account.setFollowType(Account.followAction.BLOCK); @@ -172,7 +136,7 @@ public class AccountsListAdapter extends BaseAdapter implements OnPostActionInte holder.account_follow_request.setVisibility(View.GONE); } - + holder.account_container.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -232,9 +196,20 @@ public class AccountsListAdapter extends BaseAdapter implements OnPostActionInte } }); - return convertView; } + @Override + public long getItemId(int position) { + return position; + } + + @Override + public int getItemCount() { + return accounts.size(); + } + + + @Override public void onPostAction(int statusCode, API.StatusAction statusAction, String targetedId, Error error) { if( error != null){ @@ -272,7 +247,7 @@ public class AccountsListAdapter extends BaseAdapter implements OnPostActionInte } - private class ViewHolder { + private class ViewHolder extends RecyclerView.ViewHolder{ ImageView account_pp; TextView account_ac; TextView account_dn; @@ -284,6 +259,21 @@ public class AccountsListAdapter extends BaseAdapter implements OnPostActionInte FloatingActionButton account_follow; TextView account_follow_request; LinearLayout account_container; + + ViewHolder(View itemView) { + super(itemView); + account_pp = itemView.findViewById(R.id.account_pp); + account_dn = itemView.findViewById(R.id.account_dn); + account_ac = itemView.findViewById(R.id.account_ac); + account_un = itemView.findViewById(R.id.account_un); + account_ds = itemView.findViewById(R.id.account_ds); + account_sc = itemView.findViewById(R.id.account_sc); + account_fgc = itemView.findViewById(R.id.account_fgc); + account_frc = itemView.findViewById(R.id.account_frc); + account_follow = itemView.findViewById(R.id.account_follow); + account_follow_request = itemView.findViewById(R.id.account_follow_request); + account_container = itemView.findViewById(R.id.account_container); + } } } \ No newline at end of file From f6ad7d74e2183023d742f2ccf5f5bd85194d8988 Mon Sep 17 00:00:00 2001 From: stom79 Date: Tue, 24 Oct 2017 11:44:07 +0200 Subject: [PATCH 07/46] Fixes some issues --- .../activities/RemoteFollowActivity.java | 22 +++++----- .../fragments/DisplayAccountsFragment.java | 43 +++++++++++-------- 2 files changed, 35 insertions(+), 30 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java index fd9293fce..f1949ef8c 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java @@ -28,6 +28,7 @@ import android.support.design.widget.FloatingActionButton; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; @@ -40,7 +41,6 @@ import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; -import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; @@ -98,7 +98,7 @@ public class RemoteFollowActivity extends AppCompatActivity implements OnRetriev private EditText rf_username; private TextView rf_no_result; private Button rf_search; - private ListView lv_account; + private RecyclerView lv_account; private RelativeLayout loader; private boolean isLoadingInstance; private String instance_name, screen_name; @@ -115,12 +115,12 @@ public class RemoteFollowActivity extends AppCompatActivity implements OnRetriev } setContentView(R.layout.activity_remote_follow); - rf_instance = (AutoCompleteTextView) findViewById(R.id.rf_instance); - rf_username = (EditText) findViewById(R.id.rf_username); - rf_search = (Button) findViewById(R.id.rf_search); - loader = (RelativeLayout) findViewById(R.id.loader); - lv_account = (ListView) findViewById(R.id.lv_account); - rf_no_result = (TextView) findViewById(R.id.rf_no_result); + rf_instance = findViewById(R.id.rf_instance); + rf_username = findViewById(R.id.rf_username); + rf_search = findViewById(R.id.rf_search); + loader = findViewById(R.id.loader); + lv_account = findViewById(R.id.lv_account); + rf_no_result = findViewById(R.id.rf_no_result); if( theme == Helper.THEME_LIGHT) { rf_search.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white)); } @@ -131,10 +131,10 @@ public class RemoteFollowActivity extends AppCompatActivity implements OnRetriev @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.conversation_action_bar, null); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); - TextView title = (TextView) actionBar.getCustomView().findViewById(R.id.toolbar_title); - pp_actionBar = (ImageView) actionBar.getCustomView().findViewById(R.id.pp_actionBar); + TextView title = actionBar.getCustomView().findViewById(R.id.toolbar_title); + pp_actionBar = actionBar.getCustomView().findViewById(R.id.pp_actionBar); title.setText(R.string.remote_follow_menu); - ImageView close_conversation = (ImageView) actionBar.getCustomView().findViewById(R.id.close_conversation); + ImageView close_conversation = actionBar.getCustomView().findViewById(R.id.close_conversation); if( close_conversation != null){ close_conversation.setOnClickListener(new View.OnClickListener() { @Override diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayAccountsFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayAccountsFragment.java index 15a31fc67..9d0b500d8 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayAccountsFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayAccountsFragment.java @@ -22,11 +22,11 @@ import android.os.Parcelable; import android.support.v4.app.Fragment; import android.support.v4.view.ViewCompat; import android.support.v4.widget.SwipeRefreshLayout; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.AbsListView; -import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Toast; @@ -63,7 +63,7 @@ public class DisplayAccountsFragment extends Fragment implements OnRetrieveAccou private SwipeRefreshLayout swipeRefreshLayout; private String targetedId; private boolean swiped; - private ListView lv_accounts; + private RecyclerView lv_accounts; boolean hideHeader; @Override @@ -109,23 +109,28 @@ public class DisplayAccountsFragment extends Fragment implements OnRetrieveAccou //Hide account header when scrolling for ShowAccountActivity if (hideHeader && Build.VERSION.SDK_INT >= 21) ViewCompat.setNestedScrollingEnabled(lv_accounts, true); - lv_accounts.setOnScrollListener(new AbsListView.OnScrollListener() { - @Override - public void onScrollStateChanged(AbsListView view, int scrollState) { - - } - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - if (firstVisibleItem + visibleItemCount == totalItemCount) { - if (!flag_loading) { - flag_loading = true; - if (type != RetrieveAccountsAsyncTask.Type.FOLLOWERS && type != RetrieveAccountsAsyncTask.Type.FOLLOWING) - asyncTask = new RetrieveAccountsAsyncTask(context, type, max_id, DisplayAccountsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - else - asyncTask = new RetrieveAccountsAsyncTask(context, type, targetedId, max_id, DisplayAccountsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - nextElementLoader.setVisibility(View.VISIBLE); + final LinearLayoutManager mLayoutManager; + mLayoutManager = new LinearLayoutManager(context); + lv_accounts.setLayoutManager(mLayoutManager); + lv_accounts.addOnScrollListener(new RecyclerView.OnScrollListener() { + public void onScrolled(RecyclerView recyclerView, int dx, int dy) + { + if(dy > 0) { + int visibleItemCount = mLayoutManager.getChildCount(); + int totalItemCount = mLayoutManager.getItemCount(); + int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); + if (firstVisibleItem + visibleItemCount == totalItemCount) { + if (!flag_loading) { + flag_loading = true; + if (type != RetrieveAccountsAsyncTask.Type.FOLLOWERS && type != RetrieveAccountsAsyncTask.Type.FOLLOWING) + asyncTask = new RetrieveAccountsAsyncTask(context, type, max_id, DisplayAccountsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + else + asyncTask = new RetrieveAccountsAsyncTask(context, type, targetedId, max_id, DisplayAccountsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + nextElementLoader.setVisibility(View.VISIBLE); + } + } else { + nextElementLoader.setVisibility(View.GONE); } - } else { - nextElementLoader.setVisibility(View.GONE); } } }); From c0122eef63a57bbd31e2784d1ea66d887d21424d Mon Sep 17 00:00:00 2001 From: stom79 Date: Tue, 24 Oct 2017 14:06:28 +0200 Subject: [PATCH 08/46] Last improvements --- .../fragments/DisplayStatusFragment.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java index ce3262439..18f353866 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java @@ -76,6 +76,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn private int positionSpinnerTrans; private String lastReadStatus; private Intent streamingFederatedIntent, streamingLocalIntent; + LinearLayoutManager mLayoutManager; public DisplayStatusFragment(){ } @@ -129,16 +130,14 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn nextElementLoader.setVisibility(View.GONE); statusListAdapter = new StatusListAdapter(context, type, targetedId, isOnWifi, behaviorWithAttachments, positionSpinnerTrans, this.statuses); lv_status.setAdapter(statusListAdapter); + mLayoutManager = new LinearLayoutManager(context); + lv_status.setLayoutManager(mLayoutManager); if( !comesFromSearch){ //Hide account header when scrolling for ShowAccountActivity if (hideHeader) ViewCompat.setNestedScrollingEnabled(lv_status, true); - final LinearLayoutManager mLayoutManager; - mLayoutManager = new LinearLayoutManager(context); - lv_status.setLayoutManager(mLayoutManager); - lv_status.addOnScrollListener(new RecyclerView.OnScrollListener() { public void onScrolled(RecyclerView recyclerView, int dx, int dy) { @@ -331,7 +330,11 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn status.setReplies(new ArrayList()); status.setNew(false); statuses.add(0, status); - statusListAdapter.notifyDataSetChanged(); + int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); + if( firstVisibleItem > 0) + statusListAdapter.notifyItemInserted(0); + else + statusListAdapter.notifyDataSetChanged(); knownId.add(0, status.getId()); if (textviewNoAction.getVisibility() == View.VISIBLE) textviewNoAction.setVisibility(View.GONE); @@ -376,7 +379,6 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn retrieveMissingToots(statuses.get(0).getId()); } } - statusListAdapter.notifyDataSetChanged(); } /** @@ -505,11 +507,13 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn @Override public void onRetrieveMissingFeeds(List statuses) { if( statuses != null && statuses.size() > 0) { + int inserted = 0; for (int i = statuses.size() - 1; i >= 0; i--) { if (!knownId.contains(statuses.get(i).getId())) { if (type == RetrieveFeedsAsyncTask.Type.HOME) statuses.get(i).setNew(true); knownId.add(0,statuses.get(i).getId()); + inserted++; statuses.get(i).setReplies(new ArrayList()); this.statuses.add(0, statuses.get(i)); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); @@ -518,7 +522,7 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn MainActivity.countNewStatus++; } } - statusListAdapter.notifyDataSetChanged(); + statusListAdapter.notifyItemRangeInserted(0, inserted - 1); try { ((MainActivity) context).updateHomeCounter(); }catch (Exception ignored){} From 979423818ba0b9f0cffd9bbb0de6422209e5076e Mon Sep 17 00:00:00 2001 From: stom79 Date: Tue, 24 Oct 2017 14:30:07 +0200 Subject: [PATCH 09/46] Update notification fragment --- .../DisplayNotificationsFragment.java | 59 ++++++++++--------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java index 25a8722c1..2f5f58d8b 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayNotificationsFragment.java @@ -19,12 +19,11 @@ import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; -import android.util.Log; +import android.support.v7.widget.LinearLayoutManager; +import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.AbsListView; -import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Toast; import java.util.ArrayList; @@ -60,9 +59,10 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve private boolean firstLoad; private SwipeRefreshLayout swipeRefreshLayout; private boolean swiped; - private ListView lv_notifications; + private RecyclerView lv_notifications; private String lastReadNotifications; private String userId; + LinearLayoutManager mLayoutManager; public DisplayNotificationsFragment(){ } @@ -78,12 +78,12 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve notifications = new ArrayList<>(); swiped = false; - swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeContainer); + swipeRefreshLayout = rootView.findViewById(R.id.swipeContainer); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - lv_notifications = (ListView) rootView.findViewById(R.id.lv_notifications); - mainLoader = (RelativeLayout) rootView.findViewById(R.id.loader); - nextElementLoader = (RelativeLayout) rootView.findViewById(R.id.loading_next_notifications); - textviewNoAction = (RelativeLayout) rootView.findViewById(R.id.no_action); + lv_notifications = rootView.findViewById(R.id.lv_notifications); + mainLoader = rootView.findViewById(R.id.loader); + nextElementLoader = rootView.findViewById(R.id.loading_next_notifications); + textviewNoAction = rootView.findViewById(R.id.no_action); mainLoader.setVisibility(View.VISIBLE); nextElementLoader.setVisibility(View.GONE); boolean isOnWifi = Helper.isOnWIFI(context); @@ -92,21 +92,24 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve lastReadNotifications = sharedpreferences.getString(Helper.LAST_NOTIFICATION_MAX_ID + userId, null); notificationsListAdapter = new NotificationsListAdapter(context,isOnWifi, behaviorWithAttachments,this.notifications); lv_notifications.setAdapter(notificationsListAdapter); - lv_notifications.setOnScrollListener(new AbsListView.OnScrollListener() { - @Override - public void onScrollStateChanged(AbsListView view, int scrollState) { - - } - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - - if(firstVisibleItem + visibleItemCount == totalItemCount ) { - if(!flag_loading ) { - flag_loading = true; - asyncTask = new RetrieveNotificationsAsyncTask(context, null, null, max_id, null, null,DisplayNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - nextElementLoader.setVisibility(View.VISIBLE); + mLayoutManager = new LinearLayoutManager(context); + lv_notifications.setLayoutManager(mLayoutManager); + lv_notifications.addOnScrollListener(new RecyclerView.OnScrollListener() { + public void onScrolled(RecyclerView recyclerView, int dx, int dy) + { + if(dy > 0) { + int visibleItemCount = mLayoutManager.getChildCount(); + int totalItemCount = mLayoutManager.getItemCount(); + int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); + if (firstVisibleItem + visibleItemCount == totalItemCount) { + if (!flag_loading) { + flag_loading = true; + asyncTask = new RetrieveNotificationsAsyncTask(context, null, null, max_id, null, null, DisplayNotificationsFragment.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + nextElementLoader.setVisibility(View.VISIBLE); + } + } else { + nextElementLoader.setVisibility(View.GONE); } - } else { - nextElementLoader.setVisibility(View.GONE); } } }); @@ -256,13 +259,13 @@ public class DisplayNotificationsFragment extends Fragment implements OnRetrieve if( notification != null){ //Update the id of the last notification retrieved MainActivity.lastNotificationId = notification.getId(); - int index = lv_notifications.getFirstVisiblePosition() + 1; - View v = lv_notifications.getChildAt(0); - int top = (v == null) ? 0 : v.getTop(); notifications.add(0, notification); MainActivity.countNewNotifications++; - notificationsListAdapter.notifyDataSetChanged(); - lv_notifications.setSelectionFromTop(index, top); + int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); + if( firstVisibleItem > 0) + notificationsListAdapter.notifyItemInserted(0); + else + notificationsListAdapter.notifyDataSetChanged(); if( textviewNoAction.getVisibility() == View.VISIBLE) textviewNoAction.setVisibility(View.GONE); } From c490eba5b0563d50c990b92b3f40c299d53da7a6 Mon Sep 17 00:00:00 2001 From: stom79 Date: Tue, 24 Oct 2017 14:33:14 +0200 Subject: [PATCH 10/46] Update notification adapter --- .../drawers/NotificationsListAdapter.java | 113 +++++++++--------- 1 file changed, 54 insertions(+), 59 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/NotificationsListAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/NotificationsListAdapter.java index b98d162ea..7b4e6ef54 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/NotificationsListAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/NotificationsListAdapter.java @@ -31,6 +31,7 @@ import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.PopupMenu; +import android.support.v7.widget.RecyclerView; import android.text.Html; import android.text.SpannableString; import android.text.method.LinkMovementMethod; @@ -39,7 +40,6 @@ import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; -import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; @@ -85,7 +85,8 @@ import static fr.gouv.etalab.mastodon.helper.Helper.changeDrawableColor; * Created by Thomas on 24/04/2017. * Adapter for Status */ -public class NotificationsListAdapter extends BaseAdapter implements OnPostActionInterface, OnPostNotificationsActionInterface, OnRetrieveEmojiInterface { + +public class NotificationsListAdapter extends RecyclerView.Adapter implements OnPostActionInterface, OnPostNotificationsActionInterface, OnRetrieveEmojiInterface { private Context context; private List notifications; @@ -109,65 +110,18 @@ public class NotificationsListAdapter extends BaseAdapter implements OnPostActio .cacheOnDisk(true).resetViewBeforeLoading(true).build(); } - + @Override - public int getCount() { - return notifications.size(); + public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { + return new ViewHolder(layoutInflater.inflate(R.layout.drawer_notification, parent, false)); } @Override - public Object getItem(int position) { - return notifications.get(position); - } - - @Override - public long getItemId(int position) { - return position; - } - - - @Override - public View getView(final int position, View convertView, ViewGroup parent) { + public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) { + final NotificationsListAdapter.ViewHolder holder = (NotificationsListAdapter.ViewHolder) viewHolder; final Notification notification = notifications.get(position); - final ViewHolder holder; - if (convertView == null) { - convertView = layoutInflater.inflate(R.layout.drawer_notification, parent, false); - holder = new ViewHolder(); - holder.card_status_container = (CardView) convertView.findViewById(R.id.card_status_container); - holder.notification_status_container = (LinearLayout) convertView.findViewById(R.id.notification_status_container); - holder.status_document_container = (LinearLayout) convertView.findViewById(R.id.status_document_container); - holder.notification_status_content = (TextView) convertView.findViewById(R.id.notification_status_content); - holder.notification_account_username = (TextView) convertView.findViewById(R.id.notification_account_username); - holder.notification_type = (TextView) convertView.findViewById(R.id.notification_type); - holder.notification_account_profile = (ImageView) convertView.findViewById(R.id.notification_account_profile); - holder.status_favorite_count = (TextView) convertView.findViewById(R.id.status_favorite_count); - holder.status_reblog_count = (TextView) convertView.findViewById(R.id.status_reblog_count); - holder.status_date = (TextView) convertView.findViewById(R.id.status_date); - holder.status_reply = (ImageView) convertView.findViewById(R.id.status_reply); - holder.status_privacy = (ImageView) convertView.findViewById(R.id.status_privacy); - holder.notification_delete = (ImageView) convertView.findViewById(R.id.notification_delete); - - holder.status_show_more = (Button) convertView.findViewById(R.id.status_show_more); - holder.status_prev1 = (ImageView) convertView.findViewById(R.id.status_prev1); - holder.status_prev2 = (ImageView) convertView.findViewById(R.id.status_prev2); - holder.status_prev3 = (ImageView) convertView.findViewById(R.id.status_prev3); - holder.status_prev4 = (ImageView) convertView.findViewById(R.id.status_prev4); - holder.status_prev1_play = (ImageView) convertView.findViewById(R.id.status_prev1_play); - holder.status_prev2_play = (ImageView) convertView.findViewById(R.id.status_prev2_play); - holder.status_prev3_play = (ImageView) convertView.findViewById(R.id.status_prev3_play); - holder.status_prev4_play = (ImageView) convertView.findViewById(R.id.status_prev4_play); - holder.status_container2 = (LinearLayout) convertView.findViewById(R.id.status_container2); - holder.status_container3 = (LinearLayout) convertView.findViewById(R.id.status_container3); - holder.status_prev4_container = (RelativeLayout) convertView.findViewById(R.id.status_prev4_container); - holder.status_action_container = (LinearLayout) convertView.findViewById(R.id.status_action_container); - holder.status_more = (ImageView) convertView.findViewById(R.id.status_more); - convertView.setTag(holder); - } else { - holder = (ViewHolder) convertView.getTag(); - } - final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); int iconSizePercent = sharedpreferences.getInt(Helper.SET_ICON_SIZE, 130); @@ -296,7 +250,7 @@ public class NotificationsListAdapter extends BaseAdapter implements OnPostActio content = content.substring(0, content.length() - 10); } - SpannableString spannableString = Helper.clickableElements(context, status.getContent(), + SpannableString spannableString = Helper.clickableElements(context, content, status.getReblog() != null?status.getReblog().getMentions():status.getMentions(), status.getReblog() != null?status.getReblog().getEmojis():status.getEmojis(), position, @@ -539,7 +493,6 @@ public class NotificationsListAdapter extends BaseAdapter implements OnPostActio }); holder.notification_account_username.setVisibility(View.GONE); - final View finalConvertView = convertView; final String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); final View attached = holder.status_more; holder.status_more.setOnClickListener(new View.OnClickListener() { @@ -628,7 +581,7 @@ public class NotificationsListAdapter extends BaseAdapter implements OnPostActio @Override public void run() { - Bitmap bitmap = Helper.convertTootIntoBitmap(context, finalConvertView); + Bitmap bitmap = Helper.convertTootIntoBitmap(context, holder.notification_status_container); status.setTakingScreenShot(false); notificationsListAdapter.notifyDataSetChanged(); Intent intent = new Intent(context, TootActivity.class); @@ -709,7 +662,17 @@ public class NotificationsListAdapter extends BaseAdapter implements OnPostActio //Profile picture imageLoader.displayImage(notification.getAccount().getAvatar(), holder.notification_account_profile, options); - return convertView; + + } + + @Override + public long getItemId(int position) { + return position; + } + + @Override + public int getItemCount() { + return notifications.size(); } @@ -923,7 +886,8 @@ public class NotificationsListAdapter extends BaseAdapter implements OnPostActio } - private class ViewHolder { + class ViewHolder extends RecyclerView.ViewHolder { + CardView card_status_container; TextView notification_status_content; TextView notification_type; @@ -951,6 +915,37 @@ public class NotificationsListAdapter extends BaseAdapter implements OnPostActio LinearLayout status_container3; LinearLayout notification_status_container; ImageView status_privacy; + + public ViewHolder(View itemView) { + super(itemView); + card_status_container = itemView.findViewById(R.id.card_status_container); + notification_status_container = itemView.findViewById(R.id.notification_status_container); + status_document_container = itemView.findViewById(R.id.status_document_container); + notification_status_content = itemView.findViewById(R.id.notification_status_content); + notification_account_username = itemView.findViewById(R.id.notification_account_username); + notification_type = itemView.findViewById(R.id.notification_type); + notification_account_profile = itemView.findViewById(R.id.notification_account_profile); + status_favorite_count = itemView.findViewById(R.id.status_favorite_count); + status_reblog_count = itemView.findViewById(R.id.status_reblog_count); + status_date = itemView.findViewById(R.id.status_date); + status_reply = itemView.findViewById(R.id.status_reply); + status_privacy = itemView.findViewById(R.id.status_privacy); + notification_delete = itemView.findViewById(R.id.notification_delete); + status_show_more = itemView.findViewById(R.id.status_show_more); + status_prev1 = itemView.findViewById(R.id.status_prev1); + status_prev2 = itemView.findViewById(R.id.status_prev2); + status_prev3 = itemView.findViewById(R.id.status_prev3); + status_prev4 = itemView.findViewById(R.id.status_prev4); + status_prev1_play = itemView.findViewById(R.id.status_prev1_play); + status_prev2_play = itemView.findViewById(R.id.status_prev2_play); + status_prev3_play = itemView.findViewById(R.id.status_prev3_play); + status_prev4_play = itemView.findViewById(R.id.status_prev4_play); + status_container2 = itemView.findViewById(R.id.status_container2); + status_container3 = itemView.findViewById(R.id.status_container3); + status_prev4_container = itemView.findViewById(R.id.status_prev4_container); + status_action_container = itemView.findViewById(R.id.status_action_container); + status_more = itemView.findViewById(R.id.status_more); + } } } \ No newline at end of file From 41eaabf5178acee35a71e416acd5983566aac207 Mon Sep 17 00:00:00 2001 From: stom79 Date: Tue, 24 Oct 2017 14:35:19 +0200 Subject: [PATCH 11/46] Updates listview into recyclerview --- app/src/main/res/layout/fragment_notifications.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/res/layout/fragment_notifications.xml b/app/src/main/res/layout/fragment_notifications.xml index d1dd13d21..419d366ad 100644 --- a/app/src/main/res/layout/fragment_notifications.xml +++ b/app/src/main/res/layout/fragment_notifications.xml @@ -27,14 +27,14 @@ android:layout_width="match_parent" android:id="@+id/swipeContainer" android:layout_height="match_parent"> - - + Date: Tue, 24 Oct 2017 16:02:21 +0200 Subject: [PATCH 12/46] Removes improvements which are not related to this branch --- .../etalab/mastodon/activities/BaseMainActivity.java | 2 -- app/src/main/res/layout/activity_main.xml | 10 ---------- 2 files changed, 12 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java index b12a3e71f..fb043bd3e 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java @@ -179,9 +179,7 @@ public abstract class BaseMainActivity extends AppCompatActivity Helper.fillMapEmoji(getApplicationContext()); //Here, the user is authenticated Toolbar toolbar = findViewById(R.id.toolbar); - Toolbar toolbarBottom = findViewById(R.id.toolbarBottom); setSupportActionBar(toolbar); - setSupportActionBar(toolbarBottom); toolbarTitle = toolbar.findViewById(R.id.toolbar_title); toolbar_search = toolbar.findViewById(R.id.toolbar_search); tabLayout = findViewById(R.id.tabLayout); diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 78e4f4b4d..0b6317ddf 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -39,7 +39,6 @@ - Date: Wed, 25 Oct 2017 07:53:31 +0200 Subject: [PATCH 13/46] Manages accounts in context --- .../mastodon/activities/TootActivity.java | 46 ++++++++- .../RetrieveAccountsForReplyAsyncTask.java | 95 +++++++++++++++++++ .../drawers/AccountsSearchAdapter.java | 3 +- .../OnRetrieveAccountsReplyInterface.java | 27 ++++++ 4 files changed, 169 insertions(+), 2 deletions(-) create mode 100644 app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java create mode 100644 app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnRetrieveAccountsReplyInterface.java diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java index cc5ac4846..acff2f44f 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java @@ -101,10 +101,13 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import cz.msebera.android.httpclient.Header; +import fr.gouv.etalab.mastodon.asynctasks.PostActionAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.PostStatusAsyncTask; +import fr.gouv.etalab.mastodon.asynctasks.RetrieveAccountsForReplyAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.RetrieveSearchAccountsAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.RetrieveSearchAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.UploadActionAsyncTask; +import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.client.Entities.Attachment; @@ -121,6 +124,7 @@ import fr.gouv.etalab.mastodon.drawers.TagsListAdapter; import fr.gouv.etalab.mastodon.drawers.TagsSearchAdapter; import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnPostStatusActionInterface; +import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAccountsReplyInterface; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAttachmentInterface; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveSearcAccountshInterface; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveSearchInterface; @@ -139,7 +143,7 @@ import static fr.gouv.etalab.mastodon.helper.Helper.changeDrawableColor; * Toot activity class */ -public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAccountshInterface, OnRetrieveAttachmentInterface, OnPostStatusActionInterface, OnRetrieveSearchInterface { +public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAccountshInterface, OnRetrieveAttachmentInterface, OnPostStatusActionInterface, OnRetrieveSearchInterface, OnRetrieveAccountsReplyInterface { private String visibility; @@ -766,6 +770,12 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc dialog.dismiss(); } }); + alert.setPositiveButton(R.string.accounts, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + new RetrieveAccountsForReplyAsyncTask(getApplicationContext(), tootReply, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + dialog.dismiss(); + } + }); alert.show(); return true; case R.id.action_microphone: @@ -1529,4 +1539,38 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc } + @Override + public void onRetrieveAccountsReply(ArrayList mentions) { + ArrayList accounts = new ArrayList<>(); + for(Mention mention: mentions) { + Account account = new Account(); + account.setAcct(mention.getAcct()); + account.setAvatar(mention.getUrl()); + account.setUsername(mention.getUsername()); + } + AlertDialog.Builder builderSingle = new AlertDialog.Builder(TootActivity.this); + builderSingle.setTitle(getString(R.string.choose_accounts)); + final AccountsSearchAdapter accountsSearchAdapter = new AccountsSearchAdapter(getApplicationContext(), accounts, false); + final Account[] accountArray = new Account[accounts.size()]; + int i = 0; + for(Account account: accounts){ + accountArray[i] = account; + i++; + } + builderSingle.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); + builderSingle.setAdapter(accountsSearchAdapter, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + Account selectedAccount = accountArray[which]; + + dialog.dismiss(); + } + }); + builderSingle.show(); + } } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java new file mode 100644 index 000000000..58d28de25 --- /dev/null +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java @@ -0,0 +1,95 @@ +/* Copyright 2017 Thomas Schneider + * + * This file is a part of Mastalab + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * Mastalab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even + * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General + * Public License for more details. + * + * You should have received a copy of the GNU General Public License along with Mastalab; if not, + * see . */ +package fr.gouv.etalab.mastodon.asynctasks; + +import android.content.Context; +import android.os.AsyncTask; + +import java.util.ArrayList; + +import fr.gouv.etalab.mastodon.client.API; +import fr.gouv.etalab.mastodon.client.Entities.Mention; +import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAccountsReplyInterface; + + +/** + * Created by Thomas on 25/10/2017. + * Retrieves accounts which are involved in a conversation + */ + +public class RetrieveAccountsForReplyAsyncTask extends AsyncTask { + + private Context context; + private fr.gouv.etalab.mastodon.client.Entities.Status status; + private OnRetrieveAccountsReplyInterface listener; + private ArrayList mentions; + private ArrayList addedAccounts; + + public RetrieveAccountsForReplyAsyncTask(Context context, fr.gouv.etalab.mastodon.client.Entities.Status status, OnRetrieveAccountsReplyInterface onRetrieveAccountsReplyInterface){ + this.context = context; + this.status = status; + this.listener = onRetrieveAccountsReplyInterface; + } + + @Override + protected Void doInBackground(Void... params) { + API api = new API(context); + fr.gouv.etalab.mastodon.client.Entities.Context statusContext = api.getStatusContext(status.getId()); + mentions = new ArrayList<>(); + addedAccounts = new ArrayList<>(); + //Retrieves the first toot + if( statusContext.getAncestors().size() > 0 ) { + fr.gouv.etalab.mastodon.client.Entities.Status statusFirst = statusContext.getAncestors().get(0); + statusContext = api.getStatusContext(statusContext.getAncestors().get(0).getId()); + } + if( status != null){ + for(Mention mention : status.getMentions()){ + if( canBeAdded(mention.getAcct())){ + mentions.add(mention); + addedAccounts.add(mention.getAcct()); + } + } + } + if( statusContext != null && statusContext.getDescendants().size() > 0){ + for(fr.gouv.etalab.mastodon.client.Entities.Status status : statusContext.getDescendants()) + for(Mention mention : status.getMentions()){ + if( canBeAdded(mention.getAcct())){ + mentions.add(mention); + addedAccounts.add(mention.getAcct()); + } + } + } + if( statusContext != null && statusContext.getAncestors().size() > 0){ + for(fr.gouv.etalab.mastodon.client.Entities.Status status : statusContext.getAncestors()) + for(Mention mention : status.getMentions()){ + if( canBeAdded(mention.getAcct())){ + mentions.add(mention); + addedAccounts.add(mention.getAcct()); + } + } + } + return null; + } + + private boolean canBeAdded(String acct){ + return acct != null && !acct.equals(status.getAccount().getAcct()) && !addedAccounts.contains(acct); + } + + @Override + protected void onPostExecute(Void result) { + listener.onRetrieveAccountsReply(mentions); + } + +} diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/AccountsSearchAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/AccountsSearchAdapter.java index 9b85465b1..9dabde5e0 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/AccountsSearchAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/AccountsSearchAdapter.java @@ -36,6 +36,7 @@ import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer; import java.util.ArrayList; import java.util.List; import fr.gouv.etalab.mastodon.client.Entities.Account; +import fr.gouv.etalab.mastodon.client.Entities.Mention; import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.sqlite.AccountDAO; import fr.gouv.etalab.mastodon.sqlite.Sqlite; @@ -67,7 +68,6 @@ public class AccountsSearchAdapter extends ArrayAdapter implements Filt .cacheOnDisk(true).resetViewBeforeLoading(true).build(); this.owner = false; } - public AccountsSearchAdapter(Context context, List accounts, boolean owner){ super(context, android.R.layout.simple_list_item_1, accounts); this.accounts = accounts; @@ -81,6 +81,7 @@ public class AccountsSearchAdapter extends ArrayAdapter implements Filt this.owner = owner; } + @Override public int getCount() { return accounts.size(); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnRetrieveAccountsReplyInterface.java b/app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnRetrieveAccountsReplyInterface.java new file mode 100644 index 000000000..b20f946c1 --- /dev/null +++ b/app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnRetrieveAccountsReplyInterface.java @@ -0,0 +1,27 @@ +/* Copyright 2017 Thomas Schneider + * + * This file is a part of Mastalab + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * Mastalab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even + * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General + * Public License for more details. + * + * You should have received a copy of the GNU General Public License along with Mastalab; if not, + * see . */ +package fr.gouv.etalab.mastodon.interfaces; + + +import java.util.ArrayList; +import fr.gouv.etalab.mastodon.client.Entities.Mention; + +/** + * Created by Thomas on 25/10/2017. + * Interface when accounts of a conversation have been retrieved + */ +public interface OnRetrieveAccountsReplyInterface { + void onRetrieveAccountsReply(ArrayList mentions); +} From d90801095555ea7666b2e186a0f6023a4500fda4 Mon Sep 17 00:00:00 2001 From: stom79 Date: Wed, 25 Oct 2017 09:04:34 +0200 Subject: [PATCH 14/46] Adds users in a list --- .../mastodon/activities/TootActivity.java | 31 ++- .../RetrieveAccountsForReplyAsyncTask.java | 13 +- .../etalab/mastodon/helper/CrossActions.java | 197 ------------------ 3 files changed, 32 insertions(+), 209 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java index acff2f44f..066dc96b2 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java @@ -97,6 +97,7 @@ import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; +import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -770,9 +771,9 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc dialog.dismiss(); } }); - alert.setPositiveButton(R.string.accounts, new DialogInterface.OnClickListener() { + alert.setNegativeButton(R.string.accounts, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { - new RetrieveAccountsForReplyAsyncTask(getApplicationContext(), tootReply, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + new RetrieveAccountsForReplyAsyncTask(getApplicationContext(), tootReply.getReblog() != null?tootReply.getReblog():tootReply, TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); dialog.dismiss(); } }); @@ -1542,33 +1543,43 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc @Override public void onRetrieveAccountsReply(ArrayList mentions) { ArrayList accounts = new ArrayList<>(); + List listItems = new ArrayList<>(); + final boolean[] checkedValues = new boolean[mentions.size()]; + int i = 0; for(Mention mention: mentions) { Account account = new Account(); account.setAcct(mention.getAcct()); account.setAvatar(mention.getUrl()); account.setUsername(mention.getUsername()); + listItems.add("@"+mention.getAcct()); + checkedValues[i] = toot_content.getText().toString().contains("@" + mention.getAcct()); + i++; } - AlertDialog.Builder builderSingle = new AlertDialog.Builder(TootActivity.this); + final CharSequence[] charSequenceItems = listItems.toArray(new CharSequence[listItems.size()]); + final AlertDialog.Builder builderSingle = new AlertDialog.Builder(TootActivity.this); builderSingle.setTitle(getString(R.string.choose_accounts)); final AccountsSearchAdapter accountsSearchAdapter = new AccountsSearchAdapter(getApplicationContext(), accounts, false); final Account[] accountArray = new Account[accounts.size()]; - int i = 0; + i = 0; for(Account account: accounts){ accountArray[i] = account; i++; } - builderSingle.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + builderSingle.setNegativeButton(R.string.validate, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); - builderSingle.setAdapter(accountsSearchAdapter, new DialogInterface.OnClickListener() { + + builderSingle.setMultiChoiceItems(charSequenceItems, checkedValues, new DialogInterface.OnMultiChoiceClickListener() { @Override - public void onClick(DialogInterface dialog, int which) { - Account selectedAccount = accountArray[which]; - - dialog.dismiss(); + public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) { + if (isChecked) { + toot_content.setText(charSequenceItems[indexSelected] + " " + toot_content.getText()); + } else { + toot_content.setText(toot_content.getText().toString().replaceAll("\\s*" +charSequenceItems[indexSelected], "")); + } } }); builderSingle.show(); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java index 58d28de25..c459d3b60 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java @@ -15,13 +15,19 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; +import android.content.SharedPreferences; +import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import java.util.ArrayList; import fr.gouv.etalab.mastodon.client.API; +import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.client.Entities.Mention; +import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAccountsReplyInterface; +import fr.gouv.etalab.mastodon.sqlite.AccountDAO; +import fr.gouv.etalab.mastodon.sqlite.Sqlite; /** @@ -51,7 +57,6 @@ public class RetrieveAccountsForReplyAsyncTask extends AsyncTask(); //Retrieves the first toot if( statusContext.getAncestors().size() > 0 ) { - fr.gouv.etalab.mastodon.client.Entities.Status statusFirst = statusContext.getAncestors().get(0); statusContext = api.getStatusContext(statusContext.getAncestors().get(0).getId()); } if( status != null){ @@ -84,7 +89,11 @@ public class RetrieveAccountsForReplyAsyncTask extends AsyncTask accounts = connectedAccounts(context, status, limitedToOwner); - final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); - doAction = makeAction; - boolean undoAction = (doAction == API.StatusAction.UNPIN || doAction == API.StatusAction.UNREBLOG || doAction == API.StatusAction.UNFAVOURITE ); - //Undo actions won't ask for choosing a user - if( accounts.size() == 1 || (undoAction && limitedToOwner) ) { - - boolean confirmation = false; - if( doAction == API.StatusAction.UNFAVOURITE || doAction == API.StatusAction.FAVOURITE) - confirmation = sharedpreferences.getBoolean(Helper.SET_NOTIF_VALIDATION_FAV, false); - else if( doAction == API.StatusAction.UNREBLOG || doAction == API.StatusAction.REBLOG ) - confirmation = sharedpreferences.getBoolean(Helper.SET_NOTIF_VALIDATION, true); - if (confirmation) - displayConfirmationDialog(context, doAction, status, baseAdapter, onPostActionInterface); - else { - if( doAction == API.StatusAction.REBLOG || doAction == API.StatusAction.UNREBLOG) - reblogAction(context, status, baseAdapter, onPostActionInterface); - else if( doAction == API.StatusAction.FAVOURITE || doAction == API.StatusAction.UNFAVOURITE) - favouriteAction(context, status, baseAdapter, onPostActionInterface); - else if ( doAction == API.StatusAction.PIN || doAction == API.StatusAction.UNPIN) - pinAction(context, status, baseAdapter, onPostActionInterface); - } - }else { - AlertDialog.Builder builderSingle = new AlertDialog.Builder(context); - builderSingle.setTitle(context.getString(R.string.choose_accounts)); - final AccountsSearchAdapter accountsSearchAdapter = new AccountsSearchAdapter(context, accounts, true); - final Account[] accountArray = new Account[accounts.size()]; - int i = 0; - for(Account account: accounts){ - accountArray[i] = account; - i++; - } - - builderSingle.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - }); - builderSingle.setAdapter(accountsSearchAdapter, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - - Account selectedAccount = accountArray[which]; - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - Account loggedAccount = new AccountDAO(context, db).getAccountByID(userId); - //Cross action can only be create elements (boost/fav) - if( doAction == API.StatusAction.UNREBLOG) - doAction = API.StatusAction.REBLOG; - else if( doAction == API.StatusAction.UNFAVOURITE) - doAction = API.StatusAction.FAVOURITE; - - if(loggedAccount.getInstance().equals(selectedAccount.getInstance())){ - new PostActionAsyncTask(context, selectedAccount, doAction, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - }else{ //Account is from another instance - new PostActionAsyncTask(context, selectedAccount, status, doAction, onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } - if( selectedAccount.getInstance().equals(loggedAccount.getInstance()) && selectedAccount.getId().equals(loggedAccount.getId())) { - if (doAction == API.StatusAction.REBLOG) { - status.setReblogged(true); - } else if (doAction == API.StatusAction.FAVOURITE) { - status.setFavourited(true); - } else if (doAction == API.StatusAction.PIN) { - status.setPinned(true); - } - baseAdapter.notifyDataSetChanged(); - } - dialog.dismiss(); - } - }); - builderSingle.show(); - } - } - - - - /** - * Display a validation message - * @param action int - * @param status Status - */ - private static void displayConfirmationDialog(final Context context, final API.StatusAction action, final Status status, final BaseAdapter baseAdapter, final OnPostActionInterface onPostActionInterface){ - - String title = null; - if( action == API.StatusAction.FAVOURITE){ - title = context.getString(R.string.favourite_add); - }else if( action == API.StatusAction.UNFAVOURITE){ - title = context.getString(R.string.favourite_remove); - }else if( action == API.StatusAction.REBLOG){ - title = context.getString(R.string.reblog_add); - }else if(action == API.StatusAction.UNREBLOG){ - title = context.getString(R.string.reblog_remove); - }else if ( action == API.StatusAction.PIN) { - title = context.getString(R.string.pin_add); - }else if (action == API.StatusAction.UNPIN) { - title = context.getString(R.string.pin_remove); - } - - AlertDialog.Builder builder = new AlertDialog.Builder(context); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) - builder.setMessage(Html.fromHtml(status.getContent(), Html.FROM_HTML_MODE_LEGACY)); - else - //noinspection deprecation - builder.setMessage(Html.fromHtml(status.getContent())); - builder.setIcon(android.R.drawable.ic_dialog_alert) - .setTitle(title) - .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - if( action == API.StatusAction.REBLOG || action == API.StatusAction.UNREBLOG) - reblogAction(context, status, baseAdapter, onPostActionInterface); - else if( action == API.StatusAction.FAVOURITE || action == API.StatusAction.UNFAVOURITE) - favouriteAction(context, status, baseAdapter, onPostActionInterface); - else if ( action == API.StatusAction.PIN || action == API.StatusAction.UNPIN) - pinAction(context, status, baseAdapter, onPostActionInterface); - dialog.dismiss(); - } - }) - .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - } - - }) - .show(); - } - - /** - * Favourites/Unfavourites a status - * @param status Status - */ - private static void favouriteAction(Context context, Status status, BaseAdapter baseAdapter, OnPostActionInterface onPostActionInterface){ - if( status.isFavourited() || (status.getReblog() != null && status.getReblog().isFavourited())){ - new PostActionAsyncTask(context, API.StatusAction.UNFAVOURITE, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - status.setFavourited(false); - }else{ - new PostActionAsyncTask(context, API.StatusAction.FAVOURITE, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - status.setFavourited(true); - } - baseAdapter.notifyDataSetChanged(); - } - - /** - * Reblog/Unreblog a status - * @param status Status - */ - private static void reblogAction(Context context, Status status, BaseAdapter baseAdapter, OnPostActionInterface onPostActionInterface){ - if( status.isReblogged() || (status.getReblog()!= null && status.getReblog().isReblogged())){ - String statusId = status.getReblog()!=null?status.getReblog().getId():status.getId(); - new PostActionAsyncTask(context, API.StatusAction.UNREBLOG, statusId, onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - status.setReblogged(false); - }else{ - new PostActionAsyncTask(context, API.StatusAction.REBLOG, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - status.setReblogged(true); - } - baseAdapter.notifyDataSetChanged(); - } - - /** - * Pin or unpin a status - * @param status Status - */ - private static void pinAction(Context context, Status status, BaseAdapter baseAdapter, OnPostActionInterface onPostActionInterface) { - - if (status.isPinned()) { - new PostActionAsyncTask(context, API.StatusAction.UNPIN, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - status.setPinned(false); - } else { - new PostActionAsyncTask(context, API.StatusAction.PIN, status.getId(), onPostActionInterface).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - status.setPinned(true); - } - baseAdapter.notifyDataSetChanged(); - } /** @@ -286,24 +107,6 @@ public class CrossActions { } - - - - - - - - - - - - - - - - - - public static void doCrossAction(final Context context, final Status status, final API.StatusAction doAction, final RecyclerView.Adapter baseAdapter, final OnPostActionInterface onPostActionInterface, boolean limitedToOwner){ List accounts = connectedAccounts(context, status, limitedToOwner); final SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, android.content.Context.MODE_PRIVATE); From 17f4a0aa9fca409215c2926286ff377f559e44cf Mon Sep 17 00:00:00 2001 From: stom79 Date: Wed, 25 Oct 2017 09:43:38 +0200 Subject: [PATCH 15/46] Put cursor at the end --- .../etalab/mastodon/activities/TootActivity.java | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java index 066dc96b2..f9cfbaba9 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java @@ -39,14 +39,12 @@ import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.speech.RecognizerIntent; -import android.support.design.widget.FloatingActionButton; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.Html; import android.text.InputType; import android.text.TextWatcher; -import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; @@ -97,18 +95,15 @@ import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; -import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; import cz.msebera.android.httpclient.Header; -import fr.gouv.etalab.mastodon.asynctasks.PostActionAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.PostStatusAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.RetrieveAccountsForReplyAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.RetrieveSearchAccountsAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.RetrieveSearchAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.UploadActionAsyncTask; -import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.client.Entities.Attachment; @@ -117,11 +112,9 @@ import fr.gouv.etalab.mastodon.client.Entities.Mention; import fr.gouv.etalab.mastodon.client.Entities.Results; import fr.gouv.etalab.mastodon.client.Entities.Status; import fr.gouv.etalab.mastodon.client.Entities.StoredStatus; -import fr.gouv.etalab.mastodon.client.Entities.Tag; import fr.gouv.etalab.mastodon.client.PatchBaseImageDownloader; import fr.gouv.etalab.mastodon.drawers.AccountsSearchAdapter; import fr.gouv.etalab.mastodon.drawers.DraftsListAdapter; -import fr.gouv.etalab.mastodon.drawers.TagsListAdapter; import fr.gouv.etalab.mastodon.drawers.TagsSearchAdapter; import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnPostStatusActionInterface; @@ -1551,14 +1544,15 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc account.setAcct(mention.getAcct()); account.setAvatar(mention.getUrl()); account.setUsername(mention.getUsername()); + account.setDisplay_name(mention.getUsername()); listItems.add("@"+mention.getAcct()); + accounts.add(account); checkedValues[i] = toot_content.getText().toString().contains("@" + mention.getAcct()); i++; } final CharSequence[] charSequenceItems = listItems.toArray(new CharSequence[listItems.size()]); final AlertDialog.Builder builderSingle = new AlertDialog.Builder(TootActivity.this); builderSingle.setTitle(getString(R.string.choose_accounts)); - final AccountsSearchAdapter accountsSearchAdapter = new AccountsSearchAdapter(getApplicationContext(), accounts, false); final Account[] accountArray = new Account[accounts.size()]; i = 0; for(Account account: accounts){ @@ -1569,9 +1563,9 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); + toot_content.setSelection(toot_content.getText().length()); } }); - builderSingle.setMultiChoiceItems(charSequenceItems, checkedValues, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) { From c5b087c7bcc71244abc3218d25303445f943ab51 Mon Sep 17 00:00:00 2001 From: stom79 Date: Wed, 25 Oct 2017 09:46:05 +0200 Subject: [PATCH 16/46] some cleaning --- .../mastodon/activities/TootActivity.java | 49 ++++++++++--------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java index f9cfbaba9..7cd1dd3d6 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java @@ -193,7 +193,7 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); - ImageView close_toot = (ImageView) actionBar.getCustomView().findViewById(R.id.close_toot); + ImageView close_toot = actionBar.getCustomView().findViewById(R.id.close_toot); close_toot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -202,9 +202,9 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc finish(); } }); - title = (TextView) actionBar.getCustomView().findViewById(R.id.toolbar_title); - pp_actionBar = (ImageView) actionBar.getCustomView().findViewById(R.id.pp_actionBar); - pp_progress = (ProgressBar) actionBar.getCustomView().findViewById(R.id.pp_progress); + title = actionBar.getCustomView().findViewById(R.id.toolbar_title); + pp_actionBar = actionBar.getCustomView().findViewById(R.id.pp_actionBar); + pp_progress = actionBar.getCustomView().findViewById(R.id.pp_progress); } @@ -224,22 +224,22 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc options = new DisplayImageOptions.Builder().displayer(new SimpleBitmapDisplayer()).cacheInMemory(false) .cacheOnDisk(true).resetViewBeforeLoading(true).build(); - toot_it = (Button) findViewById(R.id.toot_it); - Button toot_cw = (Button) findViewById(R.id.toot_cw); - toot_space_left = (TextView) findViewById(R.id.toot_space_left); - toot_visibility = (ImageButton) findViewById(R.id.toot_visibility); - toot_picture = (ImageButton) findViewById(R.id.toot_picture); - loading_picture = (ProgressBar) findViewById(R.id.loading_picture); - toot_picture_container = (LinearLayout) findViewById(R.id.toot_picture_container); - toot_content = (AutoCompleteTextView) findViewById(R.id.toot_content); + toot_it = findViewById(R.id.toot_it); + Button toot_cw = findViewById(R.id.toot_cw); + toot_space_left = findViewById(R.id.toot_space_left); + toot_visibility = findViewById(R.id.toot_visibility); + toot_picture = findViewById(R.id.toot_picture); + loading_picture = findViewById(R.id.loading_picture); + toot_picture_container = findViewById(R.id.toot_picture_container); + toot_content = findViewById(R.id.toot_content); int newInputType = toot_content.getInputType() & (toot_content.getInputType() ^ InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE); toot_content.setInputType(newInputType); - toot_cw_content = (EditText) findViewById(R.id.toot_cw_content); - picture_scrollview = (HorizontalScrollView) findViewById(R.id.picture_scrollview); - toot_sensitive = (CheckBox) findViewById(R.id.toot_sensitive); - //search_small_container = (LinearLayout) findViewById(R.id.search_small_container); + toot_cw_content = findViewById(R.id.toot_cw_content); + picture_scrollview = findViewById(R.id.picture_scrollview); + toot_sensitive = findViewById(R.id.toot_sensitive); - drawer_layout = (LinearLayout) findViewById(R.id.drawer_layout); + + drawer_layout = findViewById(R.id.drawer_layout); drawer_layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { @@ -861,13 +861,13 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc dialogBuilder.setView(dialogView); final AlertDialog alertDialog = dialogBuilder.create(); - final DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.date_picker); - final TimePicker timePicker = (TimePicker) dialogView.findViewById(R.id.time_picker); + final DatePicker datePicker = dialogView.findViewById(R.id.date_picker); + final TimePicker timePicker = dialogView.findViewById(R.id.time_picker); timePicker.setIs24HourView(true); - Button date_time_cancel = (Button) dialogView.findViewById(R.id.date_time_cancel); - final ImageButton date_time_previous = (ImageButton) dialogView.findViewById(R.id.date_time_previous); - final ImageButton date_time_next = (ImageButton) dialogView.findViewById(R.id.date_time_next); - final ImageButton date_time_set = (ImageButton) dialogView.findViewById(R.id.date_time_set); + Button date_time_cancel = dialogView.findViewById(R.id.date_time_cancel); + final ImageButton date_time_previous = dialogView.findViewById(R.id.date_time_previous); + final ImageButton date_time_next = dialogView.findViewById(R.id.date_time_next); + final ImageButton date_time_set = dialogView.findViewById(R.id.date_time_set); //Buttons management date_time_cancel.setOnClickListener(new View.OnClickListener() { @@ -1319,7 +1319,7 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc if( childCount > 0 ){ for(int i = 0 ; i < childCount ; i++){ if( toot_picture_container.getChildAt(i) instanceof ImageView) - toRemove.add((ImageView) toot_picture_container.getChildAt(i)); + toRemove.add((ImageView)toot_picture_container.getChildAt(i)); } if( toRemove.size() > 0){ for(ImageView imageView: toRemove) @@ -1553,6 +1553,7 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc final CharSequence[] charSequenceItems = listItems.toArray(new CharSequence[listItems.size()]); final AlertDialog.Builder builderSingle = new AlertDialog.Builder(TootActivity.this); builderSingle.setTitle(getString(R.string.choose_accounts)); + //noinspection MismatchedReadAndWriteOfArray final Account[] accountArray = new Account[accounts.size()]; i = 0; for(Account account: accounts){ From f2de4e559db19600b857294cb3a321d3713b20b7 Mon Sep 17 00:00:00 2001 From: stom79 Date: Wed, 25 Oct 2017 10:51:36 +0200 Subject: [PATCH 17/46] Adds picture --- .../mastodon/activities/TootActivity.java | 48 +++---- .../RetrieveAccountsForReplyAsyncTask.java | 13 +- .../drawers/AccountsReplyAdapter.java | 126 ++++++++++++++++++ .../OnRetrieveAccountsReplyInterface.java | 5 +- .../main/res/layout/drawer_account_reply.xml | 50 +++++++ 5 files changed, 207 insertions(+), 35 deletions(-) create mode 100644 app/src/main/java/fr/gouv/etalab/mastodon/drawers/AccountsReplyAdapter.java create mode 100644 app/src/main/res/layout/drawer_account_reply.xml diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java index 7cd1dd3d6..05772bfad 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java @@ -113,6 +113,7 @@ import fr.gouv.etalab.mastodon.client.Entities.Results; import fr.gouv.etalab.mastodon.client.Entities.Status; import fr.gouv.etalab.mastodon.client.Entities.StoredStatus; import fr.gouv.etalab.mastodon.client.PatchBaseImageDownloader; +import fr.gouv.etalab.mastodon.drawers.AccountsReplyAdapter; import fr.gouv.etalab.mastodon.drawers.AccountsSearchAdapter; import fr.gouv.etalab.mastodon.drawers.DraftsListAdapter; import fr.gouv.etalab.mastodon.drawers.TagsSearchAdapter; @@ -1534,32 +1535,16 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc @Override - public void onRetrieveAccountsReply(ArrayList mentions) { - ArrayList accounts = new ArrayList<>(); - List listItems = new ArrayList<>(); - final boolean[] checkedValues = new boolean[mentions.size()]; + public void onRetrieveAccountsReply(ArrayList accounts) { + final boolean[] checkedValues = new boolean[accounts.size()]; int i = 0; - for(Mention mention: mentions) { - Account account = new Account(); - account.setAcct(mention.getAcct()); - account.setAvatar(mention.getUrl()); - account.setUsername(mention.getUsername()); - account.setDisplay_name(mention.getUsername()); - listItems.add("@"+mention.getAcct()); - accounts.add(account); - checkedValues[i] = toot_content.getText().toString().contains("@" + mention.getAcct()); + for(Account account: accounts) { + checkedValues[i] = toot_content.getText().toString().contains("@" + account.getAcct()); i++; } - final CharSequence[] charSequenceItems = listItems.toArray(new CharSequence[listItems.size()]); final AlertDialog.Builder builderSingle = new AlertDialog.Builder(TootActivity.this); - builderSingle.setTitle(getString(R.string.choose_accounts)); - //noinspection MismatchedReadAndWriteOfArray - final Account[] accountArray = new Account[accounts.size()]; - i = 0; - for(Account account: accounts){ - accountArray[i] = account; - i++; - } + AccountsReplyAdapter accountsReplyAdapter = new AccountsReplyAdapter(TootActivity.this, accounts, checkedValues); + builderSingle.setTitle(getString(R.string.choose_accounts)).setAdapter(accountsReplyAdapter, null); builderSingle.setNegativeButton(R.string.validate, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { @@ -1567,16 +1552,15 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc toot_content.setSelection(toot_content.getText().length()); } }); - builderSingle.setMultiChoiceItems(charSequenceItems, checkedValues, new DialogInterface.OnMultiChoiceClickListener() { - @Override - public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) { - if (isChecked) { - toot_content.setText(charSequenceItems[indexSelected] + " " + toot_content.getText()); - } else { - toot_content.setText(toot_content.getText().toString().replaceAll("\\s*" +charSequenceItems[indexSelected], "")); - } - } - }); builderSingle.show(); } + + public void changeAccountReply(boolean isChecked, String acct){ + if (isChecked) { + if( !toot_content.getText().toString().contains(acct)) + toot_content.setText(acct + " " + toot_content.getText()); + } else { + toot_content.setText(toot_content.getText().toString().replaceAll("\\s*" +acct, "")); + } + } } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java index c459d3b60..e177f784b 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java @@ -18,12 +18,15 @@ import android.content.Context; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; +import android.util.Log; import java.util.ArrayList; import fr.gouv.etalab.mastodon.client.API; +import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.client.Entities.Mention; +import fr.gouv.etalab.mastodon.client.Entities.Results; import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAccountsReplyInterface; import fr.gouv.etalab.mastodon.sqlite.AccountDAO; @@ -42,11 +45,13 @@ public class RetrieveAccountsForReplyAsyncTask extends AsyncTask mentions; private ArrayList addedAccounts; + private ArrayList accounts; public RetrieveAccountsForReplyAsyncTask(Context context, fr.gouv.etalab.mastodon.client.Entities.Status status, OnRetrieveAccountsReplyInterface onRetrieveAccountsReplyInterface){ this.context = context; this.status = status; this.listener = onRetrieveAccountsReplyInterface; + this.accounts = new ArrayList<>(); } @Override @@ -85,6 +90,12 @@ public class RetrieveAccountsForReplyAsyncTask extends AsyncTask. */ + + +import android.content.Context; +import android.support.annotation.NonNull; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; +import com.nostra13.universalimageloader.core.DisplayImageOptions; +import com.nostra13.universalimageloader.core.ImageLoader; +import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer; +import java.util.List; +import fr.gouv.etalab.mastodon.activities.TootActivity; +import fr.gouv.etalab.mastodon.client.Entities.Account; +import mastodon.etalab.gouv.fr.mastodon.R; + + + +/** + * Created by Thomas on 25/10/2017. + * Adapter for accounts when replying + */ +public class AccountsReplyAdapter extends BaseAdapter{ + + private List accounts; + private LayoutInflater layoutInflater; + private ImageLoader imageLoader; + private DisplayImageOptions options; + private boolean[] checked; + private Context context; + + public AccountsReplyAdapter(Context context, List accounts, boolean[] checked){ + this.accounts = accounts; + this.context = context; + layoutInflater = LayoutInflater.from(context); + imageLoader = ImageLoader.getInstance(); + options = new DisplayImageOptions.Builder().displayer(new SimpleBitmapDisplayer()).cacheInMemory(false) + .cacheOnDisk(true).resetViewBeforeLoading(true).build(); + this.checked = checked; + } + + @Override + public int getCount() { + return accounts.size(); + } + + @Override + public Account getItem(int position) { + return accounts.get(position); + } + + @Override + public long getItemId(int position) { + return position; + } + + + + @NonNull + @Override + public View getView(final int position, View convertView, @NonNull ViewGroup parent) { + + final Account account = accounts.get(position); + final ViewHolder holder; + if (convertView == null) { + convertView = layoutInflater.inflate(R.layout.drawer_account_reply, parent, false); + holder = new ViewHolder(); + holder.account_pp = convertView.findViewById(R.id.account_pp); + holder.account_dn = convertView.findViewById(R.id.account_dn); + holder.checkbox = convertView.findViewById(R.id.checkbox); + + holder.account_container = convertView.findViewById(R.id.account_container); + convertView.setTag(holder); + } else { + holder = (ViewHolder) convertView.getTag(); + } + holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { + try { + ((TootActivity) context).changeAccountReply(isChecked, "@"+account.getAcct()); + checked[position] = isChecked; + }catch (Exception ignored){} + } + }); + holder.checkbox.setChecked(checked[position]); + holder.account_dn.setText(String.format("@%s", account.getAcct())); + + //Profile picture + imageLoader.displayImage(account.getAvatar(), holder.account_pp, options); + + return convertView; + } + + + + + private class ViewHolder { + ImageView account_pp; + TextView account_dn; + CheckBox checkbox; + LinearLayout account_container; + } + + +} \ No newline at end of file diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnRetrieveAccountsReplyInterface.java b/app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnRetrieveAccountsReplyInterface.java index b20f946c1..d10835cc6 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnRetrieveAccountsReplyInterface.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnRetrieveAccountsReplyInterface.java @@ -16,12 +16,13 @@ package fr.gouv.etalab.mastodon.interfaces; import java.util.ArrayList; -import fr.gouv.etalab.mastodon.client.Entities.Mention; + +import fr.gouv.etalab.mastodon.client.Entities.Account; /** * Created by Thomas on 25/10/2017. * Interface when accounts of a conversation have been retrieved */ public interface OnRetrieveAccountsReplyInterface { - void onRetrieveAccountsReply(ArrayList mentions); + void onRetrieveAccountsReply(ArrayList accounts); } diff --git a/app/src/main/res/layout/drawer_account_reply.xml b/app/src/main/res/layout/drawer_account_reply.xml new file mode 100644 index 000000000..402f70bd6 --- /dev/null +++ b/app/src/main/res/layout/drawer_account_reply.xml @@ -0,0 +1,50 @@ + + + + + + + + \ No newline at end of file From 3988f7bc5934afbdc1b4739845e649ba34066e7c Mon Sep 17 00:00:00 2001 From: stom79 Date: Wed, 25 Oct 2017 11:00:04 +0200 Subject: [PATCH 18/46] Changes title --- .../java/fr/gouv/etalab/mastodon/activities/TootActivity.java | 2 +- app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + 6 files changed, 6 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java index 05772bfad..5ec509d46 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java @@ -1544,7 +1544,7 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc } final AlertDialog.Builder builderSingle = new AlertDialog.Builder(TootActivity.this); AccountsReplyAdapter accountsReplyAdapter = new AccountsReplyAdapter(TootActivity.this, accounts, checkedValues); - builderSingle.setTitle(getString(R.string.choose_accounts)).setAdapter(accountsReplyAdapter, null); + builderSingle.setTitle(getString(R.string.select_accounts)).setAdapter(accountsReplyAdapter, null); builderSingle.setNegativeButton(R.string.validate, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 2c0d18834..fdbfe6c69 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -426,4 +426,5 @@ Danke an: Erlauben Interaktionen zwischen den accounts? Im Browser öffnen + Select some accounts diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index c7c4c65c7..197a8d84f 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -433,4 +433,5 @@ Le pouet a été désépinglé ! Epinglés %d Ouvrir dans le navigateur + Sélectionnez des comptes \ No newline at end of file diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 0168ce138..1f124bd26 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -433,4 +433,5 @@ Met dank aan: + Select some accounts \ No newline at end of file diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 4a7335047..27027c5b3 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -432,4 +432,5 @@ Agradecimentos a: Open in browser + Select some accounts diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0ab699d97..49d626cf0 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -182,6 +182,7 @@ No draft! Choose a toot Choose an account + Select some accounts Remove draft? Click on the button to display the original toot From 54ea7201b81395bbbaa18167ebbb51853399503c Mon Sep 17 00:00:00 2001 From: stom79 Date: Wed, 25 Oct 2017 11:05:26 +0200 Subject: [PATCH 19/46] makes all content clickable --- .../gouv/etalab/mastodon/drawers/AccountsReplyAdapter.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/AccountsReplyAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/AccountsReplyAdapter.java index 9b2740d6b..b1dcf27ec 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/AccountsReplyAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/AccountsReplyAdapter.java @@ -105,7 +105,12 @@ public class AccountsReplyAdapter extends BaseAdapter{ }); holder.checkbox.setChecked(checked[position]); holder.account_dn.setText(String.format("@%s", account.getAcct())); - + holder.account_container.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + holder.checkbox.performClick(); + } + }); //Profile picture imageLoader.displayImage(account.getAvatar(), holder.account_pp, options); From d0ffd7449aa33508b1927449c5a756d551a629d3 Mon Sep 17 00:00:00 2001 From: stom79 Date: Wed, 25 Oct 2017 13:28:45 +0200 Subject: [PATCH 20/46] Fixes screen shot with mentions --- .../mastodon/drawers/NotificationsListAdapter.java | 6 +++++- .../etalab/mastodon/drawers/StatusListAdapter.java | 12 +++++++----- .../mastodon/fragments/DisplayStatusFragment.java | 6 +++++- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/NotificationsListAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/NotificationsListAdapter.java index 7b4e6ef54..632387189 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/NotificationsListAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/NotificationsListAdapter.java @@ -581,7 +581,7 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On @Override public void run() { - Bitmap bitmap = Helper.convertTootIntoBitmap(context, holder.notification_status_container); + Bitmap bitmap = Helper.convertTootIntoBitmap(context, holder.getView()); status.setTakingScreenShot(false); notificationsListAdapter.notifyDataSetChanged(); Intent intent = new Intent(context, TootActivity.class); @@ -916,6 +916,10 @@ public class NotificationsListAdapter extends RecyclerView.Adapter implements On LinearLayout notification_status_container; ImageView status_privacy; + public View getView(){ + return itemView; + } + public ViewHolder(View itemView) { super(itemView); card_status_container = itemView.findViewById(R.id.card_status_container); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java index 29902f792..4244ef7ff 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java @@ -125,7 +125,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct private String targetedId; private HashMap urlConversion; private HashMap tagConversion; - private final int HIDDEN_STATUS = 0; private final int DISPLAYED_STATUS = 1; private List pins; private int conversationPosition; @@ -220,6 +219,10 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct ImageView new_element; + public View getView(){ + return itemView; + } + ViewHolder(View itemView) { super(itemView); loader_replies = itemView.findViewById(R.id.loader_replies); @@ -274,6 +277,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct if( type == RetrieveFeedsAsyncTask.Type.HOME) { Status status = statuses.get(position); SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + int HIDDEN_STATUS = 0; if (status.getReblog() != null && !sharedpreferences.getBoolean(Helper.SET_SHOW_BOOSTS, true)) return HIDDEN_STATUS; else if (status.getIn_reply_to_id() != null && !status.getIn_reply_to_id().equals("null") && !sharedpreferences.getBoolean(Helper.SET_SHOW_REPLIES, true)) { @@ -297,9 +301,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void onBindViewHolder(final RecyclerView.ViewHolder viewHolder, @SuppressLint("RecyclerView") final int position) { - if( viewHolder.getItemViewType() == HIDDEN_STATUS){ - - }else { + if( viewHolder.getItemViewType() == DISPLAYED_STATUS){ final ViewHolder holder = (ViewHolder) viewHolder; holder.card_status_container.setVisibility(View.VISIBLE); final Status status = statuses.get(position); @@ -1093,7 +1095,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct @Override public void run() { - Bitmap bitmap = Helper.convertTootIntoBitmap(context, holder.status_content_container); + Bitmap bitmap = Helper.convertTootIntoBitmap(context, holder.getView()); status.setTakingScreenShot(false); statusListAdapter.notifyDataSetChanged(); Intent intent = new Intent(context, TootActivity.class); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java index 18f353866..c03e728d9 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java @@ -319,7 +319,11 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); if( !status.getAccount().getId().equals(userId)) MainActivity.countNewStatus++; - statusListAdapter.notifyDataSetChanged(); + int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); + if( firstVisibleItem > 0) + statusListAdapter.notifyItemInserted(0); + else + statusListAdapter.notifyDataSetChanged(); if (textviewNoAction.getVisibility() == View.VISIBLE) textviewNoAction.setVisibility(View.GONE); } From 28cc83faeec00ea19f5421d7c034f1953e8d6853 Mon Sep 17 00:00:00 2001 From: stom79 Date: Wed, 25 Oct 2017 13:45:22 +0200 Subject: [PATCH 21/46] Adds counters --- .../mastodon/activities/BaseMainActivity.java | 41 +++++++++++++++++++ .../fragments/DisplayStatusFragment.java | 6 ++- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java index fb043bd3e..719c0997f 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java @@ -438,10 +438,16 @@ public abstract class BaseMainActivity extends AppCompatActivity displayStatusFragment.scrollToTop(); break; case 2: + if( display_local) + updateTimeLine(RetrieveFeedsAsyncTask.Type.LOCAL,0); + else if( display_global) + updateTimeLine(RetrieveFeedsAsyncTask.Type.PUBLIC,0); + break; case 3: displayStatusFragment = ((DisplayStatusFragment) fragment); if( displayStatusFragment != null ) displayStatusFragment.scrollToTop(); + updateTimeLine(RetrieveFeedsAsyncTask.Type.PUBLIC,0); break; case 1: DisplayNotificationsFragment displayNotificationsFragment = ((DisplayNotificationsFragment) fragment); @@ -1386,6 +1392,41 @@ public abstract class BaseMainActivity extends AppCompatActivity } } + public void updateTimeLine(RetrieveFeedsAsyncTask.Type type, int value){ + if( type == RetrieveFeedsAsyncTask.Type.LOCAL){ + if( tabLayout.getTabAt(2) != null && display_local){ + View tabLocal = tabLayout.getTabAt(2).getCustomView(); + TextView tabCounterLocal = tabLocal.findViewById(R.id.tab_counter); + tabCounterLocal.setText(String.valueOf(value)); + if( value > 0){ + tabCounterLocal.setVisibility(View.VISIBLE); + }else { + tabCounterLocal.setVisibility(View.GONE); + } + } + }else if( type == RetrieveFeedsAsyncTask.Type.PUBLIC){ + if( tabLayout.getTabAt(3) != null && display_local){ + View tabPublic = tabLayout.getTabAt(3).getCustomView(); + TextView tabCounterPublic = tabPublic.findViewById(R.id.tab_counter); + tabCounterPublic.setText(String.valueOf(value)); + if( value > 0){ + tabCounterPublic.setVisibility(View.VISIBLE); + }else { + tabCounterPublic.setVisibility(View.GONE); + } + }else if( tabLayout.getTabAt(2) != null && !display_local && display_global){ + View tabPublic = tabLayout.getTabAt(2).getCustomView(); + TextView tabCounterPublic = tabPublic.findViewById(R.id.tab_counter); + tabCounterPublic.setText(String.valueOf(value)); + if( value > 0){ + tabCounterPublic.setVisibility(View.VISIBLE); + }else { + tabCounterPublic.setVisibility(View.GONE); + } + } + } + } + public void updateNotifCounter(){ if(tabLayout.getTabAt(1) == null) return; diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java index c03e728d9..a179cc5b4 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/fragments/DisplayStatusFragment.java @@ -24,6 +24,7 @@ import android.support.v4.view.ViewCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; +import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -528,7 +529,10 @@ public class DisplayStatusFragment extends Fragment implements OnRetrieveFeedsIn } statusListAdapter.notifyItemRangeInserted(0, inserted - 1); try { - ((MainActivity) context).updateHomeCounter(); + if( type == RetrieveFeedsAsyncTask.Type.HOME) + ((MainActivity) context).updateHomeCounter(); + else + ((MainActivity) context).updateTimeLine(type, inserted); }catch (Exception ignored){} } } From 902c80d35c2e3cc20058da874fb1fca2c2ba2fd4 Mon Sep 17 00:00:00 2001 From: stom79 Date: Thu, 26 Oct 2017 09:06:24 +0200 Subject: [PATCH 22/46] Fixes a bug with local timeline --- .../fr/gouv/etalab/mastodon/activities/BaseMainActivity.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java index 719c0997f..688705db5 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java @@ -442,6 +442,9 @@ public abstract class BaseMainActivity extends AppCompatActivity updateTimeLine(RetrieveFeedsAsyncTask.Type.LOCAL,0); else if( display_global) updateTimeLine(RetrieveFeedsAsyncTask.Type.PUBLIC,0); + displayStatusFragment = ((DisplayStatusFragment) fragment); + if( displayStatusFragment != null ) + displayStatusFragment.scrollToTop(); break; case 3: displayStatusFragment = ((DisplayStatusFragment) fragment); From 50f822dca1f95e48481819929bc84e51fa5b6c1c Mon Sep 17 00:00:00 2001 From: stom79 Date: Thu, 26 Oct 2017 11:53:28 +0200 Subject: [PATCH 23/46] Fixes a translation issue --- .../mastodon/drawers/StatusListAdapter.java | 15 ++++++++------- .../interfaces/OnTranslatedInterface.java | 4 +++- .../translation/GoogleTranslateQuery.java | 11 ++++------- .../etalab/mastodon/translation/YandexQuery.java | 7 ++++--- 4 files changed, 19 insertions(+), 18 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java index 4244ef7ff..10a754d93 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java @@ -42,6 +42,7 @@ import android.text.SpannableString; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.text.style.ForegroundColorSpan; +import android.util.Log; import android.util.Patterns; import android.util.TypedValue; import android.view.LayoutInflater; @@ -933,13 +934,13 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct i++; } if (translator == Helper.TRANS_YANDEX) - new YandexQuery(StatusListAdapter.this).getYandexTextview(position, text, currentLocale); + new YandexQuery(StatusListAdapter.this).getYandexTextview(status, text, currentLocale); else if( translator == Helper.TRANS_GOOGLE) { while( text.charAt(text.length() -1) == '\n' && text.length() > 0) text = text.substring(0, text.length() -1); text += "."; - new GoogleTranslateQuery(StatusListAdapter.this).getGoogleTextview(position, text.trim(), currentLocale); + new GoogleTranslateQuery(StatusListAdapter.this).getGoogleTextview(status, text.trim(), currentLocale); } }else { status.setTranslationShown(!status.isTranslationShown()); @@ -1410,10 +1411,10 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } @Override - public void onTranslatedTextview(int position, String translatedResult, Boolean error) { + public void onTranslatedTextview(Status status, String translatedResult, Boolean error) { if( error){ Toast.makeText(context, R.string.toast_error_translate, Toast.LENGTH_LONG).show(); - }else if( statuses.size() > position) { + }else { try { String aJsonString = null; if (translator == Helper.TRANS_YANDEX) @@ -1434,9 +1435,9 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct aJsonString = aJsonString.replace(pair.getKey().toString(), pair.getValue().toString()); itT.remove(); } - statuses.get(position).setTranslated(true); - statuses.get(position).setTranslationShown(true); - statuses.get(position).setContent_translated(aJsonString); + status.setTranslated(true); + status.setTranslationShown(true); + status.setContent_translated(aJsonString); statusListAdapter.notifyDataSetChanged(); } catch (JSONException | UnsupportedEncodingException | IllegalArgumentException e) { e.printStackTrace(); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnTranslatedInterface.java b/app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnTranslatedInterface.java index 902963b4f..d6696ae49 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnTranslatedInterface.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/interfaces/OnTranslatedInterface.java @@ -14,10 +14,12 @@ * see . */ package fr.gouv.etalab.mastodon.interfaces; +import fr.gouv.etalab.mastodon.client.Entities.Status; + /** * Created by Thomas on 03/07/2017. * Yandex client API Handler */ public interface OnTranslatedInterface { - void onTranslatedTextview(int position, String translatedResult, Boolean error); + void onTranslatedTextview(Status status, String translatedResult, Boolean error); } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/translation/GoogleTranslateQuery.java b/app/src/main/java/fr/gouv/etalab/mastodon/translation/GoogleTranslateQuery.java index 08fc06392..c26737f40 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/translation/GoogleTranslateQuery.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/translation/GoogleTranslateQuery.java @@ -14,14 +14,11 @@ * see . */ package fr.gouv.etalab.mastodon.translation; -import android.util.Log; - import com.loopj.android.http.AsyncHttpResponseHandler; import org.json.JSONException; - import cz.msebera.android.httpclient.Header; -import fr.gouv.etalab.mastodon.helper.Helper; +import fr.gouv.etalab.mastodon.client.Entities.Status; import fr.gouv.etalab.mastodon.interfaces.OnTranslatedInterface; /** @@ -37,7 +34,7 @@ public class GoogleTranslateQuery { this.listener = listenner; } - public void getGoogleTextview(final int position, final String text, final String toLanguage) throws JSONException { + public void getGoogleTextview(final Status status, final String text, final String toLanguage) throws JSONException { GoogleTranslateClient.get(text, toLanguage, new AsyncHttpResponseHandler() { @Override @@ -47,12 +44,12 @@ public class GoogleTranslateQuery { @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { String str_response = new String(response); - listener.onTranslatedTextview(position, str_response,false); + listener.onTranslatedTextview(status, str_response,false); } @Override public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { - listener.onTranslatedTextview(position, null, true); + listener.onTranslatedTextview(status, null, true); } }); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/translation/YandexQuery.java b/app/src/main/java/fr/gouv/etalab/mastodon/translation/YandexQuery.java index e3310c9d1..566e40d2e 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/translation/YandexQuery.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/translation/YandexQuery.java @@ -16,6 +16,7 @@ package fr.gouv.etalab.mastodon.translation; import com.loopj.android.http.AsyncHttpResponseHandler; import org.json.JSONException; import cz.msebera.android.httpclient.Header; +import fr.gouv.etalab.mastodon.client.Entities.Status; import fr.gouv.etalab.mastodon.interfaces.OnTranslatedInterface; /** @@ -29,7 +30,7 @@ public class YandexQuery { this.listener = listenner; } - public void getYandexTextview(final int position, final String text, final String toLanguage) throws JSONException { + public void getYandexTextview(final Status status, final String text, final String toLanguage) throws JSONException { YandexClient.get(text, toLanguage, new AsyncHttpResponseHandler() { @Override @@ -40,12 +41,12 @@ public class YandexQuery { @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { String str_response = new String(response); - listener.onTranslatedTextview(position, str_response,false); + listener.onTranslatedTextview(status, str_response,false); } @Override public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { - listener.onTranslatedTextview(position, null, true); + listener.onTranslatedTextview(status, null, true); } }); From 3bf98eff194330333a7d4bde94e16467a0943404 Mon Sep 17 00:00:00 2001 From: stom79 Date: Thu, 26 Oct 2017 16:12:47 +0200 Subject: [PATCH 24/46] Upgrades to Android Studio 3 --- .idea/misc.xml | 12 +----------- .idea/modules.xml | 4 ++-- app/build.gradle | 12 ++++++------ build.gradle | 2 +- gradle/wrapper/gradle-wrapper.properties | 4 ++-- 5 files changed, 12 insertions(+), 22 deletions(-) diff --git a/.idea/misc.xml b/.idea/misc.xml index 63f7e50d3..a49b25924 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -45,17 +45,7 @@ - - - - - - - - - - - + diff --git a/.idea/modules.xml b/.idea/modules.xml index ea58b39cf..0a7234b5e 100644 --- a/.idea/modules.xml +++ b/.idea/modules.xml @@ -2,8 +2,8 @@ - + - + \ No newline at end of file diff --git a/app/build.gradle b/app/build.gradle index a184c863a..60b0b75fa 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -31,11 +31,11 @@ allprojects { } } dependencies { - compile 'com.android.support:appcompat-v7:26.0.2' - compile 'com.android.support:design:26.0.2' - compile 'com.android.support:support-v4:26.0.2' - compile 'com.android.support:cardview-v7:26.0.2' - compile 'com.android.support:recyclerview-v7:26.0.2' + compile 'com.android.support:appcompat-v7:26.1.0' + compile 'com.android.support:design:26.1.0' + compile 'com.android.support:support-v4:26.1.0' + compile 'com.android.support:cardview-v7:26.1.0' + compile 'com.android.support:recyclerview-v7:26.1.0' compile 'com.loopj.android:android-async-http:1.4.9' compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' compile 'com.evernote:android-job:1.2.0' @@ -43,6 +43,6 @@ dependencies { compile 'com.google.code.gson:gson:2.8.0' compile 'org.jsoup:jsoup:1.10.3' compile 'de.hdodenhof:circleimageview:2.2.0' - safetynetCompile 'com.google.android.gms:play-services-safetynet:11.0.4' + safetynetCompile 'com.google.android.gms:play-services-safetynet:11.4.2' safetynetCompile 'io.github.kobakei:ratethisapp:1.2.0' } diff --git a/build.gradle b/build.gradle index c2eea8e27..c33a638bd 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:2.3.3' + classpath 'com.android.tools.build:gradle:3.0.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 6a36ad440..cc69f7ed7 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ -#Sun Apr 23 09:30:57 CEST 2017 +#Thu Oct 26 16:05:35 CEST 2017 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip From fe548dc1f10db8b4a38bcd996b3defe362a35173 Mon Sep 17 00:00:00 2001 From: stom79 Date: Thu, 26 Oct 2017 16:19:56 +0200 Subject: [PATCH 25/46] Fixes flavorDimensions --- app/build.gradle | 1 + 1 file changed, 1 insertion(+) diff --git a/app/build.gradle b/app/build.gradle index 60b0b75fa..fb8c7ca42 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -10,6 +10,7 @@ android { versionCode 64 versionName "1.5.4" } + flavorDimensions "default" buildTypes { release { minifyEnabled false From edd6410ddaa213775b237140b7d2d90112ab0a49 Mon Sep 17 00:00:00 2001 From: Jeroen Date: Thu, 26 Oct 2017 16:38:43 +0200 Subject: [PATCH 26/46] Fix typo and mistake --- app/src/main/res/values-nl/strings.xml | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 1f124bd26..d0d9f7418 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -97,8 +97,7 @@ De toot is uit jouw favorieten verwijderd! De toot is geboost! De toot is niet meer geboost! - Gedeeld via %1$s - + Geboost door %1$s Deze toot aan jouw favorieten toevoegen? Deze toot uit jouw favorieten verwijderen? @@ -107,8 +106,6 @@ Deze toot aan jouw profielpagina vastmaken? Deze toot van profielpagina losmaken? - - Negeren Blokkeren Rapporteren @@ -344,7 +341,7 @@ LED-kleur instellen: - Blaauw + Blauw Cyaan Magenta Groen @@ -433,5 +430,5 @@ Met dank aan: - Select some accounts - \ No newline at end of file + Kies enkele accounts + From 9edc71acf53cbba8d87b2425763dab133111042d Mon Sep 17 00:00:00 2001 From: stom79 Date: Thu, 26 Oct 2017 18:09:21 +0200 Subject: [PATCH 27/46] --xml --- .idea/misc.xml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.idea/misc.xml b/.idea/misc.xml index a49b25924..45cc34846 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,8 +1,5 @@ - - - Kies enkele accounts + Omschrijf dit voor mensen met een visuele beperking diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 27027c5b3..bcb6b63b1 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -433,4 +433,5 @@ Open in browser Select some accounts + Describe for the visually impaired diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 49d626cf0..4fae85ea9 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -185,6 +185,8 @@ Select some accounts Remove draft? Click on the button to display the original toot + + Describe for the visually impaired No description available! From ddc16473130944ef64b0790ead8885723268cd4e Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 10:47:29 +0200 Subject: [PATCH 30/46] Prepares AlertDialog --- .../mastodon/activities/TootActivity.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java index 2ed5fb15f..13d7ace60 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java @@ -1039,7 +1039,31 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { + AlertDialog.Builder builderInner = new AlertDialog.Builder(TootActivity.this); + builderInner.setTitle(R.string.upload_form_description); + //Text for report + EditText input = null; + input = new EditText(TootActivity.this); + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + input.setLayoutParams(lp); + builderInner.setView(input); + builderInner.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog,int which) { + dialog.dismiss(); + } + }); + final EditText finalInput = input; + builderInner.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog,int which) { + dialog.dismiss(); + } + }); + builderInner.show(); } }); } From d320d544167dfe96fdebc1d89655f5f470f0a57d Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 10:51:00 +0200 Subject: [PATCH 31/46] Updates API to read descriptions --- .../main/java/fr/gouv/etalab/mastodon/client/API.java | 3 +++ .../etalab/mastodon/client/Entities/Attachment.java | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java b/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java index 6b1a28e4c..6efbcdc3d 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java @@ -1694,6 +1694,9 @@ public class API { attachment.setId(resobj.get("id").toString()); attachment.setType(resobj.get("type").toString()); attachment.setUrl(resobj.get("url").toString()); + try { + attachment.setDescription(resobj.get("description").toString()); + }catch (JSONException ignore){} try{ attachment.setRemote_url(resobj.get("remote_url").toString()); }catch (JSONException ignore){} diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/client/Entities/Attachment.java b/app/src/main/java/fr/gouv/etalab/mastodon/client/Entities/Attachment.java index ba1dff504..6c36a6b39 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/client/Entities/Attachment.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/client/Entities/Attachment.java @@ -30,6 +30,7 @@ public class Attachment implements Parcelable { private String remote_url; private String preview_url; private String text_url; + private String description; public Attachment(Parcel in) { id = in.readString(); @@ -38,6 +39,7 @@ public class Attachment implements Parcelable { remote_url = in.readString(); preview_url = in.readString(); text_url = in.readString(); + description = in.readString(); } public static final Creator CREATOR = new Creator() { @@ -117,5 +119,14 @@ public class Attachment implements Parcelable { dest.writeString(remote_url); dest.writeString(preview_url); dest.writeString(text_url); + dest.writeString(description); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; } } From e2347ac1d52184d3d7b87ac833ff2fb139c1b2f9 Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 10:54:28 +0200 Subject: [PATCH 32/46] Update API to change media description --- .../fr/gouv/etalab/mastodon/client/API.java | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java b/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java index 6efbcdc3d..614481143 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java @@ -1299,6 +1299,42 @@ public class API { } + /** + * Changes media description + * @param mediaId String + * @param description String + * @return Attachment + */ + public Attachment updateDescription(String mediaId, String description){ + + RequestParams params = new RequestParams(); + params.put("description", description); + post(String.format("/media/%s", mediaId), 240000, params, new JsonHttpResponseHandler() { + + @Override + public void onSuccess(int statusCode, Header[] headers, JSONObject response) { + attachment = parseAttachmentResponse(response); + } + @Override + public void onSuccess(int statusCode, Header[] headers, JSONArray response) { + try { + attachment = parseAttachmentResponse(response.getJSONObject(0)); + } catch (JSONException e) { + e.printStackTrace(); + } + } + @Override + public void onFailure(int statusCode, Header[] headers, Throwable error, JSONObject response){ + setError(statusCode, error); + } + @Override + public void onFailure(int statusCode, Header[] headers, String message, Throwable error){ + setError(statusCode, error); + } + }); + return attachment; + } + /** * Retrieves Accounts and feeds when searching *synchronously* * From 42b8b744707bd100a0a380e3e2be73ad516afaaa Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 11:05:16 +0200 Subject: [PATCH 33/46] Prepares asynctask --- .../UpdateDescriptionAttachmentAsyncTask.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateDescriptionAttachmentAsyncTask.java diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateDescriptionAttachmentAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateDescriptionAttachmentAsyncTask.java new file mode 100644 index 000000000..a3d355205 --- /dev/null +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateDescriptionAttachmentAsyncTask.java @@ -0,0 +1,56 @@ +/* Copyright 2017 Thomas Schneider + * + * This file is a part of Mastalab + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License as published by the Free Software Foundation; either version 3 of the + * License, or (at your option) any later version. + * + * Mastalab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even + * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General + * Public License for more details. + * + * You should have received a copy of the GNU General Public License along with Mastalab; if not, + * see . */ +package fr.gouv.etalab.mastodon.asynctasks; + +import android.content.Context; +import android.os.AsyncTask; +import fr.gouv.etalab.mastodon.client.API; +import fr.gouv.etalab.mastodon.client.Entities.Attachment; +import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAttachmentInterface; + + +/** + * Created by Thomas on 27/10/2017. + * Updates media description + */ + +public class UpdateDescriptionAttachmentAsyncTask extends AsyncTask { + + private Context context; + private OnRetrieveAttachmentInterface listener; + private Attachment attachment; + private String mediaId, description; + private API api; + + public UpdateDescriptionAttachmentAsyncTask(Context context, String mediaId, String description, OnRetrieveAttachmentInterface onRetrieveAttachmentInterface){ + this.context = context; + this.listener = onRetrieveAttachmentInterface; + this.description = description; + this.mediaId = mediaId; + } + + @Override + protected Void doInBackground(Void... params) { + api = new API(context); + attachment = api.updateDescription(mediaId, description); + return null; + } + + @Override + protected void onPostExecute(Void result) { + listener.onRetrieveAttachment(attachment, api.getError()); + } + +} From 7e6ad2634835cd5a0cd0bf43e0d28f1b771ecf49 Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 11:15:47 +0200 Subject: [PATCH 34/46] updates description --- .../mastodon/activities/TootActivity.java | 160 ++++++++++-------- 1 file changed, 89 insertions(+), 71 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java index 13d7ace60..cd358ac08 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java @@ -43,6 +43,7 @@ import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.Html; +import android.text.InputFilter; import android.text.InputType; import android.text.TextWatcher; import android.view.LayoutInflater; @@ -103,6 +104,7 @@ import fr.gouv.etalab.mastodon.asynctasks.PostStatusAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.RetrieveAccountsForReplyAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.RetrieveSearchAccountsAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.RetrieveSearchAsyncTask; +import fr.gouv.etalab.mastodon.asynctasks.UpdateDescriptionAttachmentAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.UploadActionAsyncTask; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Account; @@ -998,81 +1000,97 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc toot_picture.setEnabled(true); return; } - toot_picture_container.setVisibility(View.VISIBLE); - if( attachment != null ){ - String url = attachment.getPreview_url(); - if( url == null || url.trim().equals("")) - url = attachment.getUrl(); - - final ImageView imageView = new ImageView(getApplicationContext()); - imageView.setId(Integer.parseInt(attachment.getId())); - imageLoader.displayImage(url, imageView, options); - LinearLayout.LayoutParams imParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); - imParams.setMargins(20, 5, 20, 5); - imParams.height = (int) Helper.convertDpToPixel(100, getApplicationContext()); - imageView.setAdjustViewBounds(true); - imageView.setScaleType(ImageView.ScaleType.FIT_XY); - final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - boolean show_media_urls = sharedpreferences.getBoolean(Helper.SET_MEDIA_URLS, true); - if( show_media_urls) { - //Adds the shorter text_url of attachment at the end of the toot
 - int selectionBefore = toot_content.getSelectionStart(); - toot_content.setText(toot_content.getText().toString() + "\n" + attachment.getText_url()); - toot_space_left.setText(String.valueOf(toot_content.length())); - //Moves the cursor - if (selectionBefore >= 0) - toot_content.setSelection(selectionBefore); + boolean alreadyAdded = false; + int index = 0; + for(Attachment attach_: this.attachments){ + if( attach_.getId().equals(attachment.getId())){ + alreadyAdded = true; + break; } - toot_picture_container.addView(imageView, attachments.size(), imParams); - imageView.setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View view) { - showRemove(imageView.getId()); - return false; - } - }); - String instanceVersion = sharedpreferences.getString(Helper.INSTANCE_VERSION, null); - if( instanceVersion != null) { - Version currentVersion = new Version(instanceVersion); - Version minVersion = new Version("2.0"); - if (currentVersion.compareTo(minVersion) == 1 || currentVersion.equals(minVersion)) { - imageView.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - AlertDialog.Builder builderInner = new AlertDialog.Builder(TootActivity.this); - builderInner.setTitle(R.string.upload_form_description); - //Text for report - EditText input = null; - input = new EditText(TootActivity.this); - LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( - LinearLayout.LayoutParams.MATCH_PARENT, - LinearLayout.LayoutParams.WRAP_CONTENT); - input.setLayoutParams(lp); - builderInner.setView(input); - builderInner.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog,int which) { - dialog.dismiss(); - } - }); - final EditText finalInput = input; - builderInner.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog,int which) { + index++; + } + if( !alreadyAdded){ + toot_picture_container.setVisibility(View.VISIBLE); + if( attachment != null ) { + String url = attachment.getPreview_url(); + if (url == null || url.trim().equals("")) + url = attachment.getUrl(); - dialog.dismiss(); - } - }); - builderInner.show(); - } - }); + final ImageView imageView = new ImageView(getApplicationContext()); + imageView.setId(Integer.parseInt(attachment.getId())); + imageLoader.displayImage(url, imageView, options); + LinearLayout.LayoutParams imParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT); + imParams.setMargins(20, 5, 20, 5); + imParams.height = (int) Helper.convertDpToPixel(100, getApplicationContext()); + imageView.setAdjustViewBounds(true); + imageView.setScaleType(ImageView.ScaleType.FIT_XY); + final SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + boolean show_media_urls = sharedpreferences.getBoolean(Helper.SET_MEDIA_URLS, true); + if (show_media_urls) { + //Adds the shorter text_url of attachment at the end of the toot
 + int selectionBefore = toot_content.getSelectionStart(); + toot_content.setText(toot_content.getText().toString() + "\n" + attachment.getText_url()); + toot_space_left.setText(String.valueOf(toot_content.length())); + //Moves the cursor + if (selectionBefore >= 0) + toot_content.setSelection(selectionBefore); + } + toot_picture_container.addView(imageView, attachments.size(), imParams); + imageView.setOnLongClickListener(new View.OnLongClickListener() { + @Override + public boolean onLongClick(View view) { + showRemove(imageView.getId()); + return false; + } + }); + String instanceVersion = sharedpreferences.getString(Helper.INSTANCE_VERSION, null); + if (instanceVersion != null) { + Version currentVersion = new Version(instanceVersion); + Version minVersion = new Version("2.0"); + if (currentVersion.compareTo(minVersion) == 1 || currentVersion.equals(minVersion)) { + imageView.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + AlertDialog.Builder builderInner = new AlertDialog.Builder(TootActivity.this); + builderInner.setTitle(R.string.upload_form_description); + //Text for report + EditText input = null; + input = new EditText(TootActivity.this); + LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( + LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams.WRAP_CONTENT); + input.setLayoutParams(lp); + builderInner.setView(input); + builderInner.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }); + final EditText finalInput = input; + finalInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(420)}); + builderInner.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + new UpdateDescriptionAttachmentAsyncTask(getApplicationContext(), attachment.getId(), finalInput.getText().toString(), TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + dialog.dismiss(); + } + }); + builderInner.show(); + } + }); + } + } + attachments.add(attachment); + if (attachments.size() < 4) + toot_picture.setEnabled(true); + toot_sensitive.setVisibility(View.VISIBLE); + picture_scrollview.setVisibility(View.VISIBLE); + }else { + if( attachments.size() > index && attachment.getDescription() != null) { + attachments.get(index).setDescription(attachment.getDescription()); } } - attachments.add(attachment); - if( attachments.size() < 4) - toot_picture.setEnabled(true); - toot_sensitive.setVisibility(View.VISIBLE); - picture_scrollview.setVisibility(View.VISIBLE); } } From 56af77cf2c5b2933271a8aae6667344a91ea285d Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 11:36:52 +0200 Subject: [PATCH 35/46] Fixes API PUT call --- .../fr/gouv/etalab/mastodon/client/API.java | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java b/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java index 614481143..bfa5e375f 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/client/API.java @@ -1309,7 +1309,7 @@ public class API { RequestParams params = new RequestParams(); params.put("description", description); - post(String.format("/media/%s", mediaId), 240000, params, new JsonHttpResponseHandler() { + put(String.format("/media/%s", mediaId), 240000, params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject response) { @@ -1842,6 +1842,21 @@ public class API { } } + private void put(String action, int timeout, RequestParams params, AsyncHttpResponseHandler responseHandler) { + try { + client.setConnectTimeout(timeout); + client.setUserAgent(USER_AGENT); + client.addHeader("Authorization", "Bearer "+prefKeyOauthTokenT); + MastalabSSLSocketFactory mastalabSSLSocketFactory = new MastalabSSLSocketFactory(MastalabSSLSocketFactory.getKeystore()); + mastalabSSLSocketFactory.setHostnameVerifier(MastalabSSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + client.setSSLSocketFactory(mastalabSSLSocketFactory); + client.put(getAbsoluteUrl(action), params, responseHandler); + } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | UnrecoverableKeyException e) { + Toast.makeText(context, R.string.toast_error,Toast.LENGTH_LONG).show(); + e.printStackTrace(); + } + } + private void delete(String action, RequestParams params, AsyncHttpResponseHandler responseHandler){ try { client.setConnectTimeout(20000); //20s timeout From fa1d976678c1b4da7bf6c1b3ca9f8970de087538 Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 11:45:37 +0200 Subject: [PATCH 36/46] Fixes input text --- .../etalab/mastodon/activities/TootActivity.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java index cd358ac08..4f704f9cd 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java @@ -1069,7 +1069,11 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc }); final EditText finalInput = input; finalInput.setFilters(new InputFilter[]{new InputFilter.LengthFilter(420)}); - builderInner.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { + if( attachment.getDescription() != null && !attachment.getDescription().equals("null")) { + finalInput.setText(attachment.getDescription()); + finalInput.setSelection(finalInput.getText().length()); + } + builderInner.setPositiveButton(R.string.validate, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new UpdateDescriptionAttachmentAsyncTask(getApplicationContext(), attachment.getId(), finalInput.getText().toString(), TootActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); @@ -1086,10 +1090,10 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc toot_picture.setEnabled(true); toot_sensitive.setVisibility(View.VISIBLE); picture_scrollview.setVisibility(View.VISIBLE); - }else { - if( attachments.size() > index && attachment.getDescription() != null) { - attachments.get(index).setDescription(attachment.getDescription()); - } + } + }else { + if( attachments.size() > index && attachment.getDescription() != null) { + attachments.get(index).setDescription(attachment.getDescription()); } } } From 1f90b26a34e8a59dcf80891a3b49f6abd2f6358c Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 13:24:01 +0200 Subject: [PATCH 37/46] Adds description to media --- .../java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java index 10a754d93..b5bbdc420 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java @@ -1268,6 +1268,8 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct if( !url.trim().contains("missing.png")) imageLoader.displayImage(url, imageView, optionsAttachment); final int finalPosition = position; + if( attachment.getDescription() != null && !attachment.getDescription().equals("null")) + imageView.setContentDescription(attachment.getDescription()); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { From f251892960376c0548d854e72977e3686af99723 Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 13:59:14 +0200 Subject: [PATCH 38/46] Adds description to media --- .../gouv/etalab/mastodon/drawers/StatusListAdapter.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java index b5bbdc420..299afc3ff 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java @@ -42,7 +42,6 @@ import android.text.SpannableString; import android.text.Spanned; import android.text.method.LinkMovementMethod; import android.text.style.ForegroundColorSpan; -import android.util.Log; import android.util.Patterns; import android.util.TypedValue; import android.view.LayoutInflater; @@ -479,7 +478,7 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct content = status.getReblog().getContent(); displayName = Helper.shortnameToUnicode(status.getReblog().getAccount().getDisplay_name(), true); username = status.getReblog().getAccount().getUsername(); - holder.status_account_displayname.setText(displayName + " " +String.format("@%s",username)); + holder.status_account_displayname.setText(String.format("%s @%s",displayName, username)); ppurl = status.getReblog().getAccount().getAvatar(); holder.status_account_displayname.setVisibility(View.VISIBLE); holder.status_account_displayname.setText(context.getResources().getString(R.string.reblog_by, status.getAccount().getUsername())); @@ -1078,8 +1077,10 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct //noinspection deprecation content = Html.fromHtml(status.getContent()).toString(); ClipData clip = ClipData.newPlainText(Helper.CLIP_BOARD, content); - clipboard.setPrimaryClip(clip); - Toast.makeText(context,R.string.clipboard,Toast.LENGTH_LONG).show(); + if( clipboard != null) { + clipboard.setPrimaryClip(clip); + Toast.makeText(context, R.string.clipboard, Toast.LENGTH_LONG).show(); + } return true; case R.id.action_share: Intent sendIntent = new Intent(Intent.ACTION_SEND); From aeafeb90792e2963d29524df4583f59d4231f89c Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 14:07:13 +0200 Subject: [PATCH 39/46] Removes setOnTouchListener --- .../mastodon/drawers/StatusListAdapter.java | 21 ------------------- 1 file changed, 21 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java index 299afc3ff..b8b5e104b 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java @@ -523,16 +523,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct return false; } }); - holder.status_content_translated.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - if (event.getAction() == MotionEvent.ACTION_DOWN) { - holder.status_content_translated.setFocusableInTouchMode(false); - holder.status_content_translated.clearFocus(); - } - return false; - } - }); holder.status_content_translated.setMovementMethod(LinkMovementMethod.getInstance()); } @@ -559,17 +549,6 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct } }); - holder.status_content.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - - if (event.getAction() == MotionEvent.ACTION_DOWN) { - holder.status_content.setFocusableInTouchMode(false); - holder.status_content.clearFocus(); - } - return false; - } - }); holder.status_content.setMovementMethod(LinkMovementMethod.getInstance()); if( status.getReblog() == null) From d0538add5c3a2f6d0871853991f595969610f7b3 Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 14:08:46 +0200 Subject: [PATCH 40/46] Fixes some codes --- .../mastodon/drawers/StatusListAdapter.java | 37 +++++++++---------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java index b8b5e104b..e37e80266 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/drawers/StatusListAdapter.java @@ -46,7 +46,6 @@ import android.util.Patterns; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.MenuItem; -import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; @@ -1449,25 +1448,25 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct private String googleTranslateToText(String text) throws JSONException, UnsupportedEncodingException{ int i = 0; - String aJsonString = ""; + StringBuilder aJsonString = new StringBuilder(); while( i < new JSONArray(new JSONArray(text).get(0).toString()).length() ) { - aJsonString += new JSONArray(new JSONArray(new JSONArray(text).get(0).toString()).get(i).toString()).get(0).toString(); + aJsonString.append(new JSONArray(new JSONArray(new JSONArray(text).get(0).toString()).get(i).toString()).get(0).toString()); i++; } //Some fixes due to translation with Google - aJsonString = aJsonString.trim(); - aJsonString = aJsonString.replace("< / "," ",">"); - aJsonString = aJsonString.replace(" <","<"); - aJsonString = aJsonString.replace(" // ","//"); - aJsonString = aJsonString.replace("// ","//"); - aJsonString = aJsonString.replace(" //","//"); - aJsonString = aJsonString.replace(" www .","www."); - aJsonString = aJsonString.replace("www .","www."); + aJsonString = new StringBuilder(aJsonString.toString().trim()); + aJsonString = new StringBuilder(aJsonString.toString().replace("< / ", " ", ">")); + aJsonString = new StringBuilder(aJsonString.toString().replace(" <", "<")); + aJsonString = new StringBuilder(aJsonString.toString().replace(" // ", "//")); + aJsonString = new StringBuilder(aJsonString.toString().replace("// ", "//")); + aJsonString = new StringBuilder(aJsonString.toString().replace(" //", "//")); + aJsonString = new StringBuilder(aJsonString.toString().replace(" www .", "www.")); + aJsonString = new StringBuilder(aJsonString.toString().replace("www .", "www.")); // This one might cause more trouble than it's worth - aJsonString = aJsonString.replaceAll("\\* \\.", "*."); + aJsonString = new StringBuilder(aJsonString.toString().replaceAll("\\* \\.", "*.")); /* Noticed that sometimes the special tags were getting messed up by Google, @@ -1475,11 +1474,11 @@ public class StatusListAdapter extends RecyclerView.Adapter implements OnPostAct But, pre-planning might save some time later... */ - aJsonString = aJsonString.replaceAll("__\\s?(u|t)\\s?(\\d+)\\s?__", "__$1$2__"); - aJsonString = aJsonString.replaceAll("%(?![0-9a-fA-F]{2})", "%25"); - aJsonString = aJsonString.replaceAll("\\+", "%2B"); - aJsonString = URLDecoder.decode(aJsonString, "UTF-8"); - return aJsonString; + aJsonString = new StringBuilder(aJsonString.toString().replaceAll("__\\s?([ut])\\s?(\\d+)\\s?__", "__$1$2__")); + aJsonString = new StringBuilder(aJsonString.toString().replaceAll("%(?![0-9a-fA-F]{2})", "%25")); + aJsonString = new StringBuilder(aJsonString.toString().replaceAll("\\+", "%2B")); + aJsonString = new StringBuilder(URLDecoder.decode(aJsonString.toString(), "UTF-8")); + return aJsonString.toString(); } From 8d7f627fb5554af139b60b6ca66d60a5d3a653a8 Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 14:19:13 +0200 Subject: [PATCH 41/46] Some cleaning --- .../gouv/etalab/mastodon/helper/Helper.java | 48 +++++++++---------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java b/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java index 03791147c..1c50fc958 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java @@ -58,9 +58,7 @@ import android.support.design.widget.NavigationView; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v4.content.ContextCompat; -import android.support.v7.app.ActionBar; import android.support.v7.widget.RecyclerView; -import android.support.v7.widget.Toolbar; import android.text.Html; import android.text.Spannable; import android.text.SpannableString; @@ -69,13 +67,11 @@ import android.text.TextPaint; import android.text.style.ClickableSpan; import android.text.style.ImageSpan; import android.util.DisplayMetrics; -import android.util.Log; import android.util.Patterns; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; -import android.view.ViewGroup; import android.view.WindowManager; import android.webkit.CookieManager; import android.webkit.MimeTypeMap; @@ -264,7 +260,6 @@ public class Helper { public static final String INTENT_ACTION = "intent_action"; //Receiver - public static final String HEADER_ACCOUNT = "header_account"; public static final String RECEIVE_DATA = "receive_data"; public static final String RECEIVE_FEDERATED_DATA = "receive_federated_data"; public static final String RECEIVE_LOCAL_DATA = "receive_local_data"; @@ -283,7 +278,7 @@ public class Helper { "(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,10}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); - public static final Pattern hashtagPattern = Pattern.compile("(#[\\w_À-ú-]{1,})"); + public static final Pattern hashtagPattern = Pattern.compile("(#[\\w_À-ú-]+)"); /** * Converts emojis in input to unicode * @param input String @@ -344,8 +339,11 @@ public class Helper { * Check if the user is connected to Internet * @return boolean */ + @SuppressWarnings("unused") public static boolean isConnectedToInternet(Context context, String instance) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + if( cm == null) + return true; NetworkInfo ni = cm.getActiveNetworkInfo(); if ( ni != null && ni.isConnected()) { try { @@ -463,6 +461,7 @@ public class Helper { */ public static boolean isOnWIFI(Context context) { ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); + assert connManager != null; NetworkInfo activeNetwork = connManager.getActiveNetworkInfo(); return (activeNetwork != null && activeNetwork.getType() == ConnectivityManager.TYPE_WIFI); } @@ -622,6 +621,7 @@ public class Helper { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(channelId, title, NotificationManager.IMPORTANCE_DEFAULT); NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + assert mNotificationManager != null; mNotificationManager.createNotificationChannel(channel); } @@ -804,10 +804,10 @@ public class Helper { */ public static void menuAccounts(final Activity activity){ - final NavigationView navigationView = (NavigationView) activity.findViewById(R.id.nav_view); + final NavigationView navigationView = activity.findViewById(R.id.nav_view); SharedPreferences mSharedPreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String currrentUserId = mSharedPreferences.getString(Helper.PREF_KEY_ID, null); - final ImageView arrow = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.owner_accounts); + final ImageView arrow = navigationView.getHeaderView(0).findViewById(R.id.owner_accounts); if( currrentUserId == null) return; @@ -886,7 +886,7 @@ public class Helper { } }); item.setActionView(R.layout.update_account); - ImageView deleteButton = (ImageView) item.getActionView().findViewById(R.id.account_remove_button); + ImageView deleteButton = item.getActionView().findViewById(R.id.account_remove_button); deleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -941,7 +941,7 @@ public class Helper { public static void changeUser(Activity activity, String userID, boolean checkItem) { - final NavigationView navigationView = (NavigationView) activity.findViewById(R.id.nav_view); + final NavigationView navigationView = activity.findViewById(R.id.nav_view); navigationView.getMenu().clear(); MainActivity.lastNotificationId = null; MainActivity.lastHomeId = null; @@ -958,7 +958,6 @@ public class Helper { navigationView.getMenu().findItem(R.id.nav_follow_request).setVisible(false); } SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - String oldUserId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.PREF_KEY_OAUTH_TOKEN, account.getToken()); editor.putString(Helper.PREF_KEY_ID, account.getId()); @@ -972,7 +971,8 @@ public class Helper { } - public static Bitmap getRoundedCornerBitmap(Bitmap bitmap,int roundPixelSize) { + @SuppressWarnings("SameParameterValue") + public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int roundPixelSize) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final Paint paint = new Paint(); @@ -1023,11 +1023,11 @@ public class Helper { * @param options DisplayImageOptions - current configuration of ImageLoader */ public static void updateHeaderAccountInfo(final Activity activity, final Account account, final View headerLayout, ImageLoader imageLoader, DisplayImageOptions options){ - ImageView profilePicture = (ImageView) headerLayout.findViewById(R.id.profilePicture); + ImageView profilePicture = headerLayout.findViewById(R.id.profilePicture); - TextView username = (TextView) headerLayout.findViewById(R.id.username); - TextView displayedName = (TextView) headerLayout.findViewById(R.id.displayedName); - ImageView header_edit_profile = (ImageView) headerLayout.findViewById(R.id.header_edit_profile); + TextView username = headerLayout.findViewById(R.id.username); + TextView displayedName = headerLayout.findViewById(R.id.displayedName); + ImageView header_edit_profile = headerLayout.findViewById(R.id.header_edit_profile); header_edit_profile.setOnClickListener(null); if( account == null ) { Helper.logout(activity); @@ -1055,7 +1055,7 @@ public class Helper { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { super.onLoadingComplete(imageUri, view, loadedImage); - LinearLayout main_header_container = (LinearLayout) headerLayout.findViewById(R.id.main_header_container); + LinearLayout main_header_container = headerLayout.findViewById(R.id.main_header_container); Bitmap workingBitmap = Bitmap.createBitmap(loadedImage); Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true); Canvas canvas = new Canvas(mutableBitmap); @@ -1070,7 +1070,7 @@ public class Helper { @Override public void onLoadingFailed(java.lang.String imageUri, android.view.View view, FailReason failReason) { - LinearLayout main_header_container = (LinearLayout) headerLayout.findViewById(R.id.main_header_container); + LinearLayout main_header_container = headerLayout.findViewById(R.id.main_header_container); main_header_container.setBackgroundResource(R.drawable.side_nav_bar); } }); @@ -1369,7 +1369,7 @@ public class Helper { public static WebView initializeWebview(Activity activity, int webviewId){ - WebView webView = (WebView) activity.findViewById(webviewId); + WebView webView = activity.findViewById(webviewId); final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); boolean javascript = sharedpreferences.getBoolean(Helper.SET_JAVASCRIPT, true); @@ -1615,8 +1615,8 @@ public class Helper { public static void switchLayout(Activity activity){ //Check if the class calling the method is an instance of MainActivity final SharedPreferences sharedpreferences = activity.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); - final NavigationView navigationView = (NavigationView) activity.findViewById(R.id.nav_view); - android.support.design.widget.TabLayout tableLayout = (android.support.design.widget.TabLayout) activity.findViewById(R.id.tabLayout); + final NavigationView navigationView = activity.findViewById(R.id.nav_view); + android.support.design.widget.TabLayout tableLayout = activity.findViewById(R.id.tabLayout); String userID = sharedpreferences.getString(Helper.PREF_KEY_ID, null); SQLiteDatabase db = Sqlite.getInstance(activity, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); Account account = new AccountDAO(activity,db).getAccountByID(userID); @@ -1641,15 +1641,15 @@ public class Helper { */ public static Bitmap convertTootIntoBitmap(Context context, View view) { - int new_element_v = 0, notification_delete_v = 0; + int new_element_v = View.VISIBLE, notification_delete_v = View.VISIBLE; //Removes some elements - ImageView new_element = (ImageView) view.findViewById(R.id.new_element); + ImageView new_element = view.findViewById(R.id.new_element); if( new_element != null) { new_element_v = new_element.getVisibility(); new_element.setVisibility(View.GONE); } - ImageView notification_delete = (ImageView) view.findViewById(R.id.notification_delete); + ImageView notification_delete = view.findViewById(R.id.notification_delete); if( notification_delete != null) { notification_delete_v = notification_delete.getVisibility(); notification_delete.setVisibility(View.GONE); From 82a7b1a0c159a618d11b33b1fc58995916a3a4fd Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 15:09:26 +0200 Subject: [PATCH 42/46] adds weak reference to context --- .../asynctasks/PostActionAsyncTask.java | 17 ++++++------- .../PostNotificationsAsyncTask.java | 10 +++++--- .../asynctasks/PostStatusAsyncTask.java | 13 +++++----- .../asynctasks/RemoveAccountAsyncTask.java | 11 +++++--- .../asynctasks/RetrieveAccountAsyncTask.java | 9 ++++--- .../RetrieveAccountInfoAsyncTask.java | 10 +++++--- .../asynctasks/RetrieveAccountsAsyncTask.java | 11 +++++--- .../RetrieveAccountsForReplyAsyncTask.java | 20 ++++++--------- .../asynctasks/RetrieveContextAsyncTask.java | 8 +++--- .../RetrieveDeveloperAccountsAsyncTask.java | 8 +++--- .../asynctasks/RetrieveFeedsAsyncTask.java | 14 +++++++---- .../RetrieveFollowRequestSentAsyncTask.java | 10 +++++--- .../RetrieveHomeTimelineServiceAsyncTask.java | 9 ++++--- .../asynctasks/RetrieveInstanceAsyncTask.java | 8 +++--- .../RetrieveManyRelationshipsAsyncTask.java | 9 ++++--- .../RetrieveMissingFeedsAsyncTask.java | 8 +++--- ...RetrieveMissingNotificationsAsyncTask.java | 11 ++++---- .../RetrieveNotificationsAsyncTask.java | 10 +++++--- .../RetrieveRelationshipAsyncTask.java | 11 ++++---- .../RetrieveRemoteAccountsAsyncTask.java | 9 ++++--- .../asynctasks/RetrieveRepliesAsyncTask.java | 9 +++---- .../RetrieveScheduledTootsAsyncTask.java | 16 ++++++------ .../RetrieveSearchAccountsAsyncTask.java | 9 ++++--- .../asynctasks/RetrieveSearchAsyncTask.java | 8 +++--- .../UpdateAccountInfoAsyncTask.java | 25 +++++++++++-------- .../UpdateAccountInfoByIDAsyncTask.java | 20 +++++++++------ .../asynctasks/UpdateCredentialAsyncTask.java | 9 ++++--- .../UpdateDescriptionAttachmentAsyncTask.java | 9 ++++--- .../asynctasks/UploadActionAsyncTask.java | 7 +++--- 29 files changed, 189 insertions(+), 139 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/PostActionAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/PostActionAsyncTask.java index 010a2ac86..c3526fcc4 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/PostActionAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/PostActionAsyncTask.java @@ -17,12 +17,12 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; +import java.lang.ref.WeakReference; import java.util.List; import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.client.Entities.Results; -import fr.gouv.etalab.mastodon.client.Entities.Status; import fr.gouv.etalab.mastodon.interfaces.OnPostActionInterface; @@ -33,7 +33,6 @@ import fr.gouv.etalab.mastodon.interfaces.OnPostActionInterface; public class PostActionAsyncTask extends AsyncTask { - private Context context; private OnPostActionInterface listener; private int statusCode; private API.StatusAction apiAction; @@ -43,17 +42,17 @@ public class PostActionAsyncTask extends AsyncTask { private API api; private Account account; private fr.gouv.etalab.mastodon.client.Entities.Status remoteStatus; - + private WeakReference contextReference; public PostActionAsyncTask(Context context, API.StatusAction apiAction, String targetedId, OnPostActionInterface onPostActionInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.listener = onPostActionInterface; this.apiAction = apiAction; this.targetedId = targetedId; } public PostActionAsyncTask(Context context, Account account, API.StatusAction apiAction, String targetedId, OnPostActionInterface onPostActionInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.listener = onPostActionInterface; this.apiAction = apiAction; this.targetedId = targetedId; @@ -61,7 +60,7 @@ public class PostActionAsyncTask extends AsyncTask { } public PostActionAsyncTask(Context context, Account account, fr.gouv.etalab.mastodon.client.Entities.Status remoteStatus, API.StatusAction apiAction, OnPostActionInterface onPostActionInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.listener = onPostActionInterface; this.apiAction = apiAction; this.remoteStatus = remoteStatus; @@ -69,7 +68,7 @@ public class PostActionAsyncTask extends AsyncTask { } public PostActionAsyncTask(Context context, API.StatusAction apiAction, String targetedId, fr.gouv.etalab.mastodon.client.Entities.Status status, String comment, OnPostActionInterface onPostActionInterface){ - this.context = context; + contextReference = new WeakReference<>(context); this.listener = onPostActionInterface; this.apiAction = apiAction; this.targetedId = targetedId; @@ -82,9 +81,9 @@ public class PostActionAsyncTask extends AsyncTask { //Remote action if( account !=null) - api = new API(context, account.getInstance(), account.getToken()); + api = new API(contextReference.get(), account.getInstance(), account.getToken()); else - api = new API(context); + api = new API(contextReference.get()); if( remoteStatus != null){ Results search = api.search(remoteStatus.getUri()); if( search != null){ diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/PostNotificationsAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/PostNotificationsAsyncTask.java index 03509c01c..2fad6791d 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/PostNotificationsAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/PostNotificationsAsyncTask.java @@ -17,6 +17,8 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Notification; @@ -30,13 +32,13 @@ import fr.gouv.etalab.mastodon.interfaces.OnPostNotificationsActionInterface; public class PostNotificationsAsyncTask extends AsyncTask { - private Context context; private OnPostNotificationsActionInterface listener; private APIResponse apiResponse; private Notification notification; + private WeakReference contextReference; public PostNotificationsAsyncTask(Context context, Notification notification, OnPostNotificationsActionInterface onPostNotificationsActionInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.listener = onPostNotificationsActionInterface; this.notification = notification; } @@ -44,9 +46,9 @@ public class PostNotificationsAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { if( notification != null) - apiResponse = new API(context).postNoticationAction(notification.getId()); + apiResponse = new API(this.contextReference.get()).postNoticationAction(notification.getId()); else //Delete all notifications - apiResponse = new API(context).postNoticationAction(null); + apiResponse = new API(this.contextReference.get()).postNoticationAction(null); return null; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/PostStatusAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/PostStatusAsyncTask.java index b8f20d848..2a80682a9 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/PostStatusAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/PostStatusAsyncTask.java @@ -16,12 +16,10 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; -import android.util.Log; - +import java.lang.ref.WeakReference; import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Account; -import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnPostStatusActionInterface; @@ -32,14 +30,15 @@ import fr.gouv.etalab.mastodon.interfaces.OnPostStatusActionInterface; public class PostStatusAsyncTask extends AsyncTask { - private Context context; private OnPostStatusActionInterface listener; private APIResponse apiResponse; private fr.gouv.etalab.mastodon.client.Entities.Status status; private Account account; + private WeakReference contextReference; + public PostStatusAsyncTask(Context context, Account account, fr.gouv.etalab.mastodon.client.Entities.Status status, OnPostStatusActionInterface onPostStatusActionInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.listener = onPostStatusActionInterface; this.status = status; this.account = account; @@ -48,9 +47,9 @@ public class PostStatusAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { if( account == null) - apiResponse = new API(context).postStatusAction(status); + apiResponse = new API(this.contextReference.get()).postStatusAction(status); else - apiResponse = new API(context, account.getInstance(), account.getToken()).postStatusAction(status); + apiResponse = new API(this.contextReference.get(), account.getInstance(), account.getToken()).postStatusAction(status); return null; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RemoveAccountAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RemoveAccountAsyncTask.java index c02454cab..f0ae3e1f0 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RemoveAccountAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RemoveAccountAsyncTask.java @@ -17,6 +17,9 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.app.Activity; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; + +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.sqlite.AccountDAO; import fr.gouv.etalab.mastodon.sqlite.Sqlite; @@ -28,18 +31,18 @@ import fr.gouv.etalab.mastodon.sqlite.Sqlite; public class RemoveAccountAsyncTask extends AsyncTask { - private Activity activity; + private WeakReference activityReference; private Account account; public RemoveAccountAsyncTask(Activity activity, Account account){ - this.activity = activity; + activityReference = new WeakReference<>(activity); this.account = account; } @Override protected Void doInBackground(Void... params) { - SQLiteDatabase db = Sqlite.getInstance(activity, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - new AccountDAO(activity, db).removeUser(account); + SQLiteDatabase db = Sqlite.getInstance(activityReference.get(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); + new AccountDAO(activityReference.get(), db).removeUser(account); return null; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountAsyncTask.java index 464f748ef..797468974 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountAsyncTask.java @@ -17,6 +17,8 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAccountInterface; import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.Entities.Account; @@ -29,21 +31,22 @@ import fr.gouv.etalab.mastodon.client.Entities.Account; public class RetrieveAccountAsyncTask extends AsyncTask { - private Context context; + private String targetedId; private Account account; private OnRetrieveAccountInterface listener; private API api; + private WeakReference contextReference; public RetrieveAccountAsyncTask(Context context, String targetedId, OnRetrieveAccountInterface onRetrieveAccountInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.targetedId = targetedId; this.listener = onRetrieveAccountInterface; } @Override protected Void doInBackground(Void... params) { - api = new API(context); + api = new API(this.contextReference.get()); account = api.getAccount(targetedId); return null; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountInfoAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountInfoAsyncTask.java index 328943546..46d6bcb3d 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountInfoAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountInfoAsyncTask.java @@ -16,6 +16,9 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; + +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAccountInterface; @@ -27,19 +30,20 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAccountInterface; public class RetrieveAccountInfoAsyncTask extends AsyncTask { - private Context context; + private OnRetrieveAccountInterface listener; private Account account; private API api; + private WeakReference contextReference; public RetrieveAccountInfoAsyncTask(Context context, OnRetrieveAccountInterface onRetrieveAccountInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.listener = onRetrieveAccountInterface; } @Override protected Void doInBackground(Void... params) { - api = new API(context); + api = new API(this.contextReference.get()); account = api.verifyCredentials(); return null; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsAsyncTask.java index a049c17c2..8b88e0784 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsAsyncTask.java @@ -16,6 +16,9 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; + +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAccountsInterface; @@ -28,12 +31,12 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAccountsInterface; public class RetrieveAccountsAsyncTask extends AsyncTask { - private Context context; private Type action; private APIResponse apiResponse; private String max_id; private OnRetrieveAccountsInterface listener; private String targetedId; + private WeakReference contextReference; public enum Type{ BLOCKED, @@ -43,7 +46,7 @@ public class RetrieveAccountsAsyncTask extends AsyncTask { } public RetrieveAccountsAsyncTask(Context context, Type action, String targetedId, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.action = action; this.max_id = max_id; this.listener = onRetrieveAccountsInterface; @@ -51,7 +54,7 @@ public class RetrieveAccountsAsyncTask extends AsyncTask { } public RetrieveAccountsAsyncTask(Context context, Type action, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.action = action; this.max_id = max_id; this.listener = onRetrieveAccountsInterface; @@ -60,7 +63,7 @@ public class RetrieveAccountsAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { - API api = new API(context); + API api = new API(this.contextReference.get()); switch (action){ case BLOCKED: apiResponse = api.getBlocks(max_id); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java index e177f784b..5c1e84f34 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveAccountsForReplyAsyncTask.java @@ -18,12 +18,9 @@ import android.content.Context; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; -import android.util.Log; - +import java.lang.ref.WeakReference; import java.util.ArrayList; - import fr.gouv.etalab.mastodon.client.API; -import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.client.Entities.Mention; import fr.gouv.etalab.mastodon.client.Entities.Results; @@ -40,15 +37,14 @@ import fr.gouv.etalab.mastodon.sqlite.Sqlite; public class RetrieveAccountsForReplyAsyncTask extends AsyncTask { - private Context context; private fr.gouv.etalab.mastodon.client.Entities.Status status; private OnRetrieveAccountsReplyInterface listener; - private ArrayList mentions; private ArrayList addedAccounts; private ArrayList accounts; + private WeakReference contextReference; public RetrieveAccountsForReplyAsyncTask(Context context, fr.gouv.etalab.mastodon.client.Entities.Status status, OnRetrieveAccountsReplyInterface onRetrieveAccountsReplyInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.status = status; this.listener = onRetrieveAccountsReplyInterface; this.accounts = new ArrayList<>(); @@ -56,9 +52,9 @@ public class RetrieveAccountsForReplyAsyncTask extends AsyncTask(); + ArrayList mentions = new ArrayList<>(); addedAccounts = new ArrayList<>(); //Retrieves the first toot if( statusContext.getAncestors().size() > 0 ) { @@ -100,10 +96,10 @@ public class RetrieveAccountsForReplyAsyncTask extends AsyncTask { - private Context context; private String statusId; private fr.gouv.etalab.mastodon.client.Entities.Status statusFirst; private fr.gouv.etalab.mastodon.client.Entities.Context statusContext; private OnRetrieveContextInterface listener; private API api; + private WeakReference contextReference; public RetrieveContextAsyncTask(Context context, String statusId, OnRetrieveContextInterface onRetrieveContextInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.statusId = statusId; this.listener = onRetrieveContextInterface; } @Override protected Void doInBackground(Void... params) { - api = new API(context); + api = new API(this.contextReference.get()); statusContext = api.getStatusContext(statusId); //Retrieves the first toot if( statusContext.getAncestors().size() > 0 ) { diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveDeveloperAccountsAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveDeveloperAccountsAsyncTask.java index 01458bf19..38b5f81e7 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveDeveloperAccountsAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveDeveloperAccountsAsyncTask.java @@ -17,6 +17,7 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; +import java.lang.ref.WeakReference; import java.util.ArrayList; import fr.gouv.etalab.mastodon.client.API; @@ -32,18 +33,19 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveSearchDevelopersAccountshInt public class RetrieveDeveloperAccountsAsyncTask extends AsyncTask { - private Context context; + private OnRetrieveSearchDevelopersAccountshInterface listener; private ArrayList accounts; + private WeakReference contextReference; public RetrieveDeveloperAccountsAsyncTask(Context context, OnRetrieveSearchDevelopersAccountshInterface onRetrieveSearchDevelopersAccountshInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.listener = onRetrieveSearchDevelopersAccountshInterface; } @Override protected Void doInBackground(Void... params) { - API api = new API(context); + API api = new API(this.contextReference.get()); accounts = new ArrayList<>(); APIResponse apiResponse = api.searchAccounts("@tom79@mastodon.social", 1); if( apiResponse.getAccounts() != null && apiResponse.getAccounts().size() > 0) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveFeedsAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveFeedsAsyncTask.java index 5787a5148..3dc81241a 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveFeedsAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveFeedsAsyncTask.java @@ -16,6 +16,9 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; + +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveFeedsInterface; @@ -28,7 +31,7 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveFeedsInterface; public class RetrieveFeedsAsyncTask extends AsyncTask { - private Context context; + private Type action; private APIResponse apiResponse; private String max_id; @@ -37,6 +40,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { private String tag; private boolean showMediaOnly = false; private boolean showPinned = false; + private WeakReference contextReference; public enum Type{ HOME, @@ -51,14 +55,14 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { } public RetrieveFeedsAsyncTask(Context context, Type action, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.action = action; this.max_id = max_id; this.listener = onRetrieveFeedsInterface; } public RetrieveFeedsAsyncTask(Context context, Type action, String targetedID, String max_id, boolean showMediaOnly, boolean showPinned, OnRetrieveFeedsInterface onRetrieveFeedsInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.action = action; this.max_id = max_id; this.listener = onRetrieveFeedsInterface; @@ -67,7 +71,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { this.showPinned = showPinned; } public RetrieveFeedsAsyncTask(Context context, Type action, String tag, String targetedID, String max_id, OnRetrieveFeedsInterface onRetrieveFeedsInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.action = action; this.max_id = max_id; this.listener = onRetrieveFeedsInterface; @@ -78,7 +82,7 @@ public class RetrieveFeedsAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { - API api = new API(context); + API api = new API(this.contextReference.get()); switch (action){ case HOME: apiResponse = api.getHomeTimeline(max_id); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveFollowRequestSentAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveFollowRequestSentAsyncTask.java index eb7e66b67..b23d478a6 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveFollowRequestSentAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveFollowRequestSentAsyncTask.java @@ -17,6 +17,8 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAccountsInterface; @@ -29,14 +31,14 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAccountsInterface; public class RetrieveFollowRequestSentAsyncTask extends AsyncTask { - private Context context; + private APIResponse apiResponse; private String max_id; private OnRetrieveAccountsInterface listener; - + private WeakReference contextReference; public RetrieveFollowRequestSentAsyncTask(Context context, String max_id, OnRetrieveAccountsInterface onRetrieveAccountsInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.max_id = max_id; this.listener = onRetrieveAccountsInterface; } @@ -44,7 +46,7 @@ public class RetrieveFollowRequestSentAsyncTask extends AsyncTask { - private Context context; private APIResponse apiResponse; private String since_id; private String acct, userId; private OnRetrieveHomeTimelineServiceInterface listener; private String instance; private String token; + private WeakReference contextReference; public RetrieveHomeTimelineServiceAsyncTask(Context context, String instance, String token, String since_id, String acct, String userId, OnRetrieveHomeTimelineServiceInterface onRetrieveHomeTimelineServiceInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.since_id = since_id; this.listener = onRetrieveHomeTimelineServiceInterface; this.acct = acct; @@ -47,7 +50,7 @@ public class RetrieveHomeTimelineServiceAsyncTask extends AsyncTask { - private Context context; private OnRetrieveInstanceInterface listener; private APIResponse apiResponse; + private WeakReference contextReference; public RetrieveInstanceAsyncTask(Context context, OnRetrieveInstanceInterface onRetrieveInstanceInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.listener = onRetrieveInstanceInterface; } @Override protected Void doInBackground(Void... params) { - apiResponse = new API(context).getInstance(); + apiResponse = new API(this.contextReference.get()).getInstance(); return null; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveManyRelationshipsAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveManyRelationshipsAsyncTask.java index d7774dd37..1fe3d3c92 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveManyRelationshipsAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveManyRelationshipsAsyncTask.java @@ -16,6 +16,8 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; + +import java.lang.ref.WeakReference; import java.util.List; import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.APIResponse; @@ -29,20 +31,21 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveManyRelationshipsInterface; public class RetrieveManyRelationshipsAsyncTask extends AsyncTask { - private Context context; + private List accounts; private OnRetrieveManyRelationshipsInterface listener; private APIResponse apiResponse; + private WeakReference contextReference; public RetrieveManyRelationshipsAsyncTask(Context context, List accounts, OnRetrieveManyRelationshipsInterface onRetrieveManyRelationshipsInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.listener = onRetrieveManyRelationshipsInterface; this.accounts = accounts; } @Override protected Void doInBackground(Void... params) { - apiResponse = new API(context).getRelationship(accounts); + apiResponse = new API(this.contextReference.get()).getRelationship(accounts); return null; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveMissingFeedsAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveMissingFeedsAsyncTask.java index 2e1950ace..f52d7c43c 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveMissingFeedsAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveMissingFeedsAsyncTask.java @@ -16,6 +16,8 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; + +import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import fr.gouv.etalab.mastodon.activities.MainActivity; @@ -31,14 +33,14 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveMissingFeedsInterface; public class RetrieveMissingFeedsAsyncTask extends AsyncTask { - private Context context; private String since_id; private OnRetrieveMissingFeedsInterface listener; private List statuses = new ArrayList<>(); private RetrieveFeedsAsyncTask.Type type; + private WeakReference contextReference; public RetrieveMissingFeedsAsyncTask(Context context, String since_id, RetrieveFeedsAsyncTask.Type type, OnRetrieveMissingFeedsInterface onRetrieveMissingFeedsInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.since_id = since_id; this.listener = onRetrieveMissingFeedsInterface; this.type = type; @@ -48,7 +50,7 @@ public class RetrieveMissingFeedsAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { int loopInc = 0; - API api = new API(context); + API api = new API(this.contextReference.get()); List tempStatus; APIResponse apiResponse = null; while (loopInc < 10){ diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveMissingNotificationsAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveMissingNotificationsAsyncTask.java index 694d625c3..5d10d1bdb 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveMissingNotificationsAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveMissingNotificationsAsyncTask.java @@ -16,8 +16,7 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; -import android.util.Log; - +import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; @@ -25,7 +24,6 @@ import fr.gouv.etalab.mastodon.activities.MainActivity; import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Notification; -import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveMissingNotificationsInterface; @@ -36,13 +34,14 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveMissingNotificationsInterfac public class RetrieveMissingNotificationsAsyncTask extends AsyncTask { - private Context context; + private String since_id; private OnRetrieveMissingNotificationsInterface listener; private List notifications = new ArrayList<>(); + private WeakReference contextReference; public RetrieveMissingNotificationsAsyncTask(Context context, String since_id, OnRetrieveMissingNotificationsInterface onRetrieveMissingNotifications){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.since_id = since_id; this.listener = onRetrieveMissingNotifications; } @@ -51,7 +50,7 @@ public class RetrieveMissingNotificationsAsyncTask extends AsyncTask tempNotifications; while (loopInc < 10){ APIResponse apiResponse = api.getNotificationsSince(since_id, 40); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveNotificationsAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveNotificationsAsyncTask.java index 6b7a8b7c6..db86366d1 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveNotificationsAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveNotificationsAsyncTask.java @@ -16,6 +16,9 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; + +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveNotificationsInterface; @@ -28,7 +31,7 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveNotificationsInterface; public class RetrieveNotificationsAsyncTask extends AsyncTask { - private Context context; + private APIResponse apiResponse; private String max_id; private String acct, userId; @@ -36,9 +39,10 @@ public class RetrieveNotificationsAsyncTask extends AsyncTask private String instance; private String token; private boolean refreshData; + private WeakReference contextReference; public RetrieveNotificationsAsyncTask(Context context, String instance, String token, String max_id, String acct, String userId, OnRetrieveNotificationsInterface onRetrieveNotificationsInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.max_id = max_id; this.listener = onRetrieveNotificationsInterface; this.acct = acct; @@ -52,7 +56,7 @@ public class RetrieveNotificationsAsyncTask extends AsyncTask @Override protected Void doInBackground(Void... params) { - API api = new API(context, instance, token); + API api = new API(this.contextReference.get(), instance, token); if( acct == null) apiResponse = api.getNotifications(max_id); else diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRelationshipAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRelationshipAsyncTask.java index 84c62d9ba..e3f02d489 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRelationshipAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRelationshipAsyncTask.java @@ -16,11 +16,9 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; -import android.util.Log; - +import java.lang.ref.WeakReference; import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.Entities.Relationship; -import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveRelationshipInterface; /** @@ -30,21 +28,22 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveRelationshipInterface; public class RetrieveRelationshipAsyncTask extends AsyncTask { - private Context context; + private String accountId; private Relationship relationship; private OnRetrieveRelationshipInterface listener; private API api; + private WeakReference contextReference; public RetrieveRelationshipAsyncTask(Context context, String accountId, OnRetrieveRelationshipInterface onRetrieveRelationshipInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.listener = onRetrieveRelationshipInterface; this.accountId = accountId; } @Override protected Void doInBackground(Void... params) { - api = new API(context); + api = new API(this.contextReference.get()); relationship = api.getRelationship(accountId); return null; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRemoteAccountsAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRemoteAccountsAsyncTask.java index 2ace2fee3..42490b581 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRemoteAccountsAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRemoteAccountsAsyncTask.java @@ -16,6 +16,9 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; + +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.Entities.Results; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveRemoteAccountInterface; @@ -30,20 +33,20 @@ public class RetrieveRemoteAccountsAsyncTask extends AsyncTask private OnRetrieveRemoteAccountInterface listener; private String url; - private Context context; private Results results; + private WeakReference contextReference; public RetrieveRemoteAccountsAsyncTask(Context context, String username, String instance, OnRetrieveRemoteAccountInterface onRetrieveRemoteAccountInterface){ this.url = "https://" + instance + "/@" + username; this.listener = onRetrieveRemoteAccountInterface; - this.context = context; + this.contextReference = new WeakReference<>(context); } @Override protected Void doInBackground(Void... params) { - API api = new API(context); + API api = new API(this.contextReference.get()); results = api.search(this.url); return null; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRepliesAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRepliesAsyncTask.java index 582b8e04d..fa6dc5fe4 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRepliesAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveRepliesAsyncTask.java @@ -18,6 +18,7 @@ import android.content.Context; import android.os.AsyncTask; import android.os.SystemClock; +import java.lang.ref.WeakReference; import java.util.List; import fr.gouv.etalab.mastodon.client.API; @@ -32,15 +33,13 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveRepliesInterface; public class RetrieveRepliesAsyncTask extends AsyncTask { - private Context context; private APIResponse apiResponse; private OnRetrieveRepliesInterface listener; private List statuses; - - + private WeakReference contextReference; public RetrieveRepliesAsyncTask(Context context, List statuses, OnRetrieveRepliesInterface onRetrieveRepliesInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.statuses = statuses; this.listener = onRetrieveRepliesInterface; } @@ -48,7 +47,7 @@ public class RetrieveRepliesAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { - API api = new API(context); + API api = new API(this.contextReference.get()); for (fr.gouv.etalab.mastodon.client.Entities.Status status : statuses) { fr.gouv.etalab.mastodon.client.Entities.Context statusContext = api.getStatusContext((status.getReblog() != null) ? status.getReblog().getId() : status.getId()); SystemClock.sleep(25); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveScheduledTootsAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveScheduledTootsAsyncTask.java index d0cf7203c..f1757ec75 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveScheduledTootsAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveScheduledTootsAsyncTask.java @@ -18,14 +18,11 @@ import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; import android.os.SystemClock; -import android.util.Log; - import com.evernote.android.job.JobManager; import com.evernote.android.job.JobRequest; - +import java.lang.ref.WeakReference; import java.util.List; import java.util.Set; - import fr.gouv.etalab.mastodon.client.Entities.StoredStatus; import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveScheduledTootsInterface; @@ -41,21 +38,22 @@ import fr.gouv.etalab.mastodon.sqlite.StatusStoredDAO; public class RetrieveScheduledTootsAsyncTask extends AsyncTask { - private Context context; + private OnRetrieveScheduledTootsInterface listener; private List storedStatuses; + private WeakReference contextReference; public RetrieveScheduledTootsAsyncTask(Context context, OnRetrieveScheduledTootsInterface onRetrieveScheduledTootsInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.listener = onRetrieveScheduledTootsInterface; } @Override protected Void doInBackground(Void... params) { - SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); + SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); //Retrieves job asked by the user - storedStatuses = new StatusStoredDAO(context, db).getAllScheduled(); + storedStatuses = new StatusStoredDAO(this.contextReference.get(), db).getAllScheduled(); //Retrieves real jobs still waiting Set jobRequests = JobManager.instance().getAllJobRequestsForTag(ScheduledTootsSyncJob.SCHEDULED_TOOT); int[] jobIds; @@ -74,7 +72,7 @@ public class RetrieveScheduledTootsAsyncTask extends AsyncTask for(StoredStatus ss: storedStatuses){ if (!Helper.isJobPresent(jobIds, ss.getJobId())){ //JobId is fixed to -1 which means an error occured (it was never sent) - new StatusStoredDAO(context, db).updateJobId(ss.getId(),-1); + new StatusStoredDAO(this.contextReference.get(), db).updateJobId(ss.getId(),-1); } } //Lets time to update db before dispaying diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveSearchAccountsAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveSearchAccountsAsyncTask.java index 764d5e7f1..1c2d81c03 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveSearchAccountsAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveSearchAccountsAsyncTask.java @@ -16,6 +16,9 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; + +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveSearcAccountshInterface; @@ -28,13 +31,13 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveSearcAccountshInterface; public class RetrieveSearchAccountsAsyncTask extends AsyncTask { - private Context context; private String query; private APIResponse apiResponse; private OnRetrieveSearcAccountshInterface listener; + private WeakReference contextReference; public RetrieveSearchAccountsAsyncTask(Context context, String query, OnRetrieveSearcAccountshInterface onRetrieveSearcAccountshInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.query = query; this.listener = onRetrieveSearcAccountshInterface; } @@ -42,7 +45,7 @@ public class RetrieveSearchAccountsAsyncTask extends AsyncTask @Override protected Void doInBackground(Void... params) { - API api = new API(context); + API api = new API(this.contextReference.get()); apiResponse = api.searchAccounts(query, 20); return null; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveSearchAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveSearchAsyncTask.java index ab969f04d..571fc9ebb 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveSearchAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/RetrieveSearchAsyncTask.java @@ -17,6 +17,8 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.Entities.Results; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveSearchInterface; @@ -29,14 +31,14 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveSearchInterface; public class RetrieveSearchAsyncTask extends AsyncTask { - private Context context; private String query; private Results results; private OnRetrieveSearchInterface listener; private API api; + private WeakReference contextReference; public RetrieveSearchAsyncTask(Context context, String query, OnRetrieveSearchInterface onRetrieveSearchInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.query = query; this.listener = onRetrieveSearchInterface; } @@ -44,7 +46,7 @@ public class RetrieveSearchAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { - api = new API(context); + api = new API(this.contextReference.get()); results = api.search(query); return null; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateAccountInfoAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateAccountInfoAsyncTask.java index ced1386bf..913057724 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateAccountInfoAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateAccountInfoAsyncTask.java @@ -20,6 +20,9 @@ import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; + +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.activities.MainActivity; import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.Entities.Account; @@ -34,36 +37,36 @@ import fr.gouv.etalab.mastodon.sqlite.AccountDAO; public class UpdateAccountInfoAsyncTask extends AsyncTask { - private Context context; private String token; private String instance; + private WeakReference contextReference; public UpdateAccountInfoAsyncTask(Context context, String token, String instance){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.token = token; this.instance = instance; } @Override protected Void doInBackground(Void... params) { - Account account = new API(context, instance, null).verifyCredentials(); - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + Account account = new API(this.contextReference.get(), instance, null).verifyCredentials(); + SharedPreferences sharedpreferences = this.contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); if( token == null) { token = sharedpreferences.getString(Helper.PREF_KEY_OAUTH_TOKEN, null); } account.setToken(token); //TODO: remove this static value to allow other instances account.setInstance(instance); - SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - boolean userExists = new AccountDAO(context, db).userExist(account); + SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); + boolean userExists = new AccountDAO(this.contextReference.get(), db).userExist(account); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Helper.PREF_KEY_ID, account.getId()); editor.apply(); if( userExists) - new AccountDAO(context, db).updateAccount(account); + new AccountDAO(this.contextReference.get(), db).updateAccount(account); else { if( account.getUsername() != null && account.getCreated_at() != null) - new AccountDAO(context, db).insertAccount(account); + new AccountDAO(this.contextReference.get(), db).insertAccount(account); } return null; } @@ -71,10 +74,10 @@ public class UpdateAccountInfoAsyncTask extends AsyncTask { @Override protected void onPostExecute(Void result) { - Intent mainActivity = new Intent(context, MainActivity.class); + Intent mainActivity = new Intent(this.contextReference.get(), MainActivity.class); mainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(mainActivity); - ((Activity) context).finish(); + this.contextReference.get().startActivity(mainActivity); + ((Activity) this.contextReference.get()).finish(); } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateAccountInfoByIDAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateAccountInfoByIDAsyncTask.java index 9ae2317c9..8374d155d 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateAccountInfoByIDAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateAccountInfoByIDAsyncTask.java @@ -18,6 +18,9 @@ import android.content.Context; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.os.AsyncTask; + +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.helper.Helper; @@ -32,28 +35,29 @@ import fr.gouv.etalab.mastodon.sqlite.Sqlite; public class UpdateAccountInfoByIDAsyncTask extends AsyncTask { - private Context context; + private OnUpdateAccountInfoInterface listener; + private WeakReference contextReference; public UpdateAccountInfoByIDAsyncTask(Context context, OnUpdateAccountInfoInterface onUpdateAccountInfoInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.listener = onUpdateAccountInfoInterface; } @Override protected Void doInBackground(Void... params) { - SharedPreferences sharedpreferences = context.getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); + SharedPreferences sharedpreferences = this.contextReference.get().getSharedPreferences(Helper.APP_PREFS, Context.MODE_PRIVATE); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - Account account = new API(context).getAccount(userId); - SQLiteDatabase db = Sqlite.getInstance(context, Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); - boolean userExists = new AccountDAO(context, db).userExist(account); + Account account = new API(this.contextReference.get()).getAccount(userId); + SQLiteDatabase db = Sqlite.getInstance(this.contextReference.get(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); + boolean userExists = new AccountDAO(this.contextReference.get(), db).userExist(account); if( userExists) { - Account accountDb = new AccountDAO(context, db).getAccountByID(userId); + Account accountDb = new AccountDAO(this.contextReference.get(), db).getAccountByID(userId); if( accountDb != null){ account.setInstance(accountDb.getInstance()); account.setToken(accountDb.getToken()); - new AccountDAO(context, db).updateAccount(account); + new AccountDAO(this.contextReference.get(), db).updateAccount(account); } } return null; diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateCredentialAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateCredentialAsyncTask.java index b54e9adcb..2b4a5defb 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateCredentialAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateCredentialAsyncTask.java @@ -17,6 +17,9 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; + +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.interfaces.OnUpdateCredentialInterface; @@ -28,13 +31,13 @@ import fr.gouv.etalab.mastodon.interfaces.OnUpdateCredentialInterface; public class UpdateCredentialAsyncTask extends AsyncTask { - private Context context; private String display_name, note, avatar, header; private APIResponse apiResponse; private OnUpdateCredentialInterface listener; + private WeakReference contextReference; public UpdateCredentialAsyncTask(Context context, String display_name, String note, String avatar, String header, OnUpdateCredentialInterface onUpdateCredentialInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.display_name = display_name; this.note = note; this.avatar = avatar; @@ -44,7 +47,7 @@ public class UpdateCredentialAsyncTask extends AsyncTask { @Override protected Void doInBackground(Void... params) { - apiResponse = new API(context).updateCredential(display_name, note, avatar, header); + apiResponse = new API(this.contextReference.get()).updateCredential(display_name, note, avatar, header); return null; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateDescriptionAttachmentAsyncTask.java b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateDescriptionAttachmentAsyncTask.java index a3d355205..2e45c3dbe 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateDescriptionAttachmentAsyncTask.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/asynctasks/UpdateDescriptionAttachmentAsyncTask.java @@ -16,6 +16,9 @@ package fr.gouv.etalab.mastodon.asynctasks; import android.content.Context; import android.os.AsyncTask; + +import java.lang.ref.WeakReference; + import fr.gouv.etalab.mastodon.client.API; import fr.gouv.etalab.mastodon.client.Entities.Attachment; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAttachmentInterface; @@ -28,14 +31,14 @@ import fr.gouv.etalab.mastodon.interfaces.OnRetrieveAttachmentInterface; public class UpdateDescriptionAttachmentAsyncTask extends AsyncTask { - private Context context; private OnRetrieveAttachmentInterface listener; private Attachment attachment; private String mediaId, description; private API api; + private WeakReference contextReference; public UpdateDescriptionAttachmentAsyncTask(Context context, String mediaId, String description, OnRetrieveAttachmentInterface onRetrieveAttachmentInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.listener = onRetrieveAttachmentInterface; this.description = description; this.mediaId = mediaId; @@ -43,7 +46,7 @@ public class UpdateDescriptionAttachmentAsyncTask extends AsyncTask { - private Context context; private OnRetrieveAttachmentInterface listener; private Attachment attachment; private InputStream inputStream; private API api; + private WeakReference contextReference; public UploadActionAsyncTask(Context context, InputStream inputStream, OnRetrieveAttachmentInterface onRetrieveAttachmentInterface){ - this.context = context; + this.contextReference = new WeakReference<>(context); this.listener = onRetrieveAttachmentInterface; this.inputStream = inputStream; } @Override protected Void doInBackground(Void... params) { - api = new API(context); + api = new API(this.contextReference.get()); attachment = api.uploadMedia(inputStream); return null; } From 400bf263ec60742719cabb0083ef3e1b1d548201 Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 15:34:53 +0200 Subject: [PATCH 43/46] Cleans code in activities --- .../mastodon/activities/AboutActivity.java | 22 +- .../activities/BaseLoginActivity.java | 1 - .../mastodon/activities/BaseMainActivity.java | 17 +- .../activities/EditProfileActivity.java | 38 +- .../mastodon/activities/HashTagActivity.java | 17 +- .../mastodon/activities/InstanceActivity.java | 14 +- .../mastodon/activities/MediaActivity.java | 19 +- .../activities/RemoteFollowActivity.java | 2 + .../activities/SearchResultActivity.java | 6 +- .../activities/ShowAccountActivity.java | 345 +++++++++--------- .../activities/ShowConversationActivity.java | 8 +- .../mastodon/activities/TootActivity.java | 43 +-- .../mastodon/activities/WebviewActivity.java | 4 +- .../activities/WebviewConnectActivity.java | 4 +- 14 files changed, 256 insertions(+), 284 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/AboutActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/AboutActivity.java index 187939e7d..b062e7a3a 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/AboutActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/AboutActivity.java @@ -23,7 +23,6 @@ import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; -import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; @@ -33,10 +32,8 @@ import android.widget.Toast; import java.util.ArrayList; import java.util.List; -import fr.gouv.etalab.mastodon.asynctasks.RetrieveDeveloperAccountsAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.RetrieveRelationshipAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.RetrieveRemoteAccountsAsyncTask; -import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Account; import fr.gouv.etalab.mastodon.client.Entities.Error; import fr.gouv.etalab.mastodon.client.Entities.Relationship; @@ -46,7 +43,6 @@ import fr.gouv.etalab.mastodon.helper.ExpandableHeightListView; import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveRelationshipInterface; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveRemoteAccountInterface; -import fr.gouv.etalab.mastodon.interfaces.OnRetrieveSearchDevelopersAccountshInterface; import mastodon.etalab.gouv.fr.mastodon.R; @@ -78,20 +74,20 @@ public class AboutActivity extends AppCompatActivity implements OnRetrieveRemote if( getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); setContentView(R.layout.activity_about); - TextView about_version = (TextView) findViewById(R.id.about_version); + TextView about_version = findViewById(R.id.about_version); try { PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); String version = pInfo.versionName; about_version.setText(getResources().getString(R.string.about_vesrion, version)); } catch (PackageManager.NameNotFoundException ignored) {} - ExpandableHeightListView lv_developers = (ExpandableHeightListView) findViewById(R.id.lv_developers); - ExpandableHeightListView lv_designers = (ExpandableHeightListView) findViewById(R.id.lv_designers); - ExpandableHeightListView lv_contributors = (ExpandableHeightListView) findViewById(R.id.lv_contributors); + ExpandableHeightListView lv_developers = findViewById(R.id.lv_developers); + ExpandableHeightListView lv_designers = findViewById(R.id.lv_designers); + ExpandableHeightListView lv_contributors = findViewById(R.id.lv_contributors); - Button about_code = (Button) findViewById(R.id.about_code); - Button about_license = (Button) findViewById(R.id.about_license); - Button about_thekinrar = (Button) findViewById(R.id.about_thekinrar); + Button about_code = findViewById(R.id.about_code); + Button about_license = findViewById(R.id.about_license); + Button about_thekinrar = findViewById(R.id.about_thekinrar); about_code.setOnClickListener(new View.OnClickListener() { @Override @@ -116,7 +112,7 @@ public class AboutActivity extends AppCompatActivity implements OnRetrieveRemote startActivity(browserIntent); } }); - Button about_translation = (Button) findViewById(R.id.about_translation); + Button about_translation = findViewById(R.id.about_translation); about_translation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -133,7 +129,7 @@ public class AboutActivity extends AppCompatActivity implements OnRetrieveRemote about_license.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white)); } - TextView about_website = (TextView) findViewById(R.id.about_website); + TextView about_website = findViewById(R.id.about_website); about_website.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseLoginActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseLoginActivity.java index e1585bf3c..40b341d77 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseLoginActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseLoginActivity.java @@ -24,7 +24,6 @@ import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; -import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java index ac5cb0d3d..90253020c 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/BaseMainActivity.java @@ -516,6 +516,7 @@ public abstract class BaseMainActivity extends AppCompatActivity public boolean onQueryTextSubmit(String query) { //Hide keyboard InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); + assert imm != null; imm.hideSoftInputFromWindow(toolbar_search.getWindowToken(), 0); Intent intent = new Intent(BaseMainActivity.this, SearchResultActivity.class); intent.putExtra("search", query); @@ -850,15 +851,14 @@ public abstract class BaseMainActivity extends AppCompatActivity * Manages new intents * @param intent Intent - intent related to a notification in top bar */ - private boolean mamageNewIntent(Intent intent){ + private void mamageNewIntent(Intent intent){ if( intent == null || intent.getExtras() == null ) - return false; + return; String action = intent.getAction(); String type = intent.getType(); Bundle extras = intent.getExtras(); String userIdIntent; - boolean matchingIntent = false; if( extras.containsKey(INTENT_ACTION) ){ final NavigationView navigationView = findViewById(R.id.nav_view); userIdIntent = extras.getString(PREF_KEY_ID); //Id of the account in the intent @@ -868,7 +868,6 @@ public abstract class BaseMainActivity extends AppCompatActivity if( tabLayout.getTabAt(1) != null) //noinspection ConstantConditions tabLayout.getTabAt(1).select(); - matchingIntent = true; }else if( extras.getInt(INTENT_ACTION) == HOME_TIMELINE_INTENT){ changeUser(BaseMainActivity.this, userIdIntent, true); //Connects the account which is related to the notification }else if( extras.getInt(INTENT_ACTION) == CHANGE_THEME_INTENT){ @@ -876,7 +875,6 @@ public abstract class BaseMainActivity extends AppCompatActivity navigationView.setCheckedItem(R.id.nav_settings); navigationView.getMenu().performIdentifierAction(R.id.nav_settings, 0); toolbarTitle.setText(R.string.settings); - matchingIntent = true; }else if( extras.getInt(INTENT_ACTION) == CHANGE_USER_INTENT){ unCheckAllMenuItems(navigationView); if( tabLayout.getTabAt(0) != null) @@ -885,7 +883,6 @@ public abstract class BaseMainActivity extends AppCompatActivity if( !toolbar_search.isIconified() ) { toolbar_search.setIconified(true); } - matchingIntent = true; } }else if( Intent.ACTION_SEND.equals(action) && type != null ) { if ("text/plain".equals(type)) { @@ -950,7 +947,6 @@ public abstract class BaseMainActivity extends AppCompatActivity intent.setAction(""); intent.setData(null); intent.setFlags(0); - return matchingIntent; } @Override @@ -1045,6 +1041,7 @@ public abstract class BaseMainActivity extends AppCompatActivity @Override public void onReceive(Context context, Intent intent) { Bundle b = intent.getExtras(); + assert b != null; userIdService = b.getString("userIdService", null); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); if( userIdService != null && userIdService.equals(userId)) { @@ -1059,6 +1056,7 @@ public abstract class BaseMainActivity extends AppCompatActivity @Override public void onReceive(Context context, Intent intent) { Bundle b = intent.getExtras(); + assert b != null; userIdService = b.getString("userIdService", null); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); if( userIdService != null && userIdService.equals(userId)) { @@ -1074,6 +1072,7 @@ public abstract class BaseMainActivity extends AppCompatActivity public void onReceive(Context context, Intent intent) { Bundle b = intent.getExtras(); StreamingService.EventStreaming eventStreaming = (StreamingService.EventStreaming) intent.getSerializableExtra("eventStreaming"); + assert b != null; userIdService = b.getString("userIdService", null); String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); if( userIdService != null && userIdService.equals(userId)) { @@ -1399,10 +1398,12 @@ public abstract class BaseMainActivity extends AppCompatActivity } } + @SuppressWarnings("ConstantConditions") public void updateTimeLine(RetrieveFeedsAsyncTask.Type type, int value){ if( type == RetrieveFeedsAsyncTask.Type.LOCAL){ if( tabLayout.getTabAt(2) != null && display_local){ View tabLocal = tabLayout.getTabAt(2).getCustomView(); + assert tabLocal != null; TextView tabCounterLocal = tabLocal.findViewById(R.id.tab_counter); tabCounterLocal.setText(String.valueOf(value)); if( value > 0){ @@ -1414,6 +1415,7 @@ public abstract class BaseMainActivity extends AppCompatActivity }else if( type == RetrieveFeedsAsyncTask.Type.PUBLIC){ if( tabLayout.getTabAt(3) != null && display_local){ View tabPublic = tabLayout.getTabAt(3).getCustomView(); + assert tabPublic != null; TextView tabCounterPublic = tabPublic.findViewById(R.id.tab_counter); tabCounterPublic.setText(String.valueOf(value)); if( value > 0){ @@ -1423,6 +1425,7 @@ public abstract class BaseMainActivity extends AppCompatActivity } }else if( tabLayout.getTabAt(2) != null && !display_local && display_global){ View tabPublic = tabLayout.getTabAt(2).getCustomView(); + assert tabPublic != null; TextView tabCounterPublic = tabPublic.findViewById(R.id.tab_counter); tabCounterPublic.setText(String.valueOf(value)); if( value > 0){ diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/EditProfileActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/EditProfileActivity.java index 4b1cff7fa..1affdbaf0 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/EditProfileActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/EditProfileActivity.java @@ -36,7 +36,6 @@ import android.text.Html; import android.text.TextWatcher; import android.util.Base64; import android.view.LayoutInflater; -import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; @@ -93,7 +92,6 @@ public class EditProfileActivity extends AppCompatActivity implements OnRetrieve private static final int PICK_IMAGE_PROFILE = 6545; private String profile_picture, header_picture, profile_username, profile_note; private Bitmap profile_picture_bmp, profile_header_bmp; - private TextView title; private ImageView pp_actionBar; @Override @@ -112,13 +110,14 @@ public class EditProfileActivity extends AppCompatActivity implements OnRetrieve ActionBar actionBar = getSupportActionBar(); if( actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(android.content.Context.LAYOUT_INFLATER_SERVICE); - View view = inflater.inflate(R.layout.conversation_action_bar, null); + assert inflater != null; + @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.conversation_action_bar, null); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); - title = (TextView) actionBar.getCustomView().findViewById(R.id.toolbar_title); - pp_actionBar = (ImageView) actionBar.getCustomView().findViewById(R.id.pp_actionBar); + TextView title = actionBar.getCustomView().findViewById(R.id.toolbar_title); + pp_actionBar = actionBar.getCustomView().findViewById(R.id.pp_actionBar); title.setText(R.string.settings_title_profile); - ImageView close_conversation = (ImageView) actionBar.getCustomView().findViewById(R.id.close_conversation); + ImageView close_conversation = actionBar.getCustomView().findViewById(R.id.close_conversation); if( close_conversation != null){ close_conversation.setOnClickListener(new View.OnClickListener() { @Override @@ -172,14 +171,14 @@ public class EditProfileActivity extends AppCompatActivity implements OnRetrieve }}); - set_profile_name = (EditText) findViewById(R.id.set_profile_name); - set_profile_description = (EditText) findViewById(R.id.set_profile_description); - set_profile_picture = (ImageView) findViewById(R.id.set_profile_picture); - set_header_picture = (ImageView) findViewById(R.id.set_header_picture); - set_change_profile_picture = (Button) findViewById(R.id.set_change_profile_picture); - set_change_header_picture = (Button) findViewById(R.id.set_change_header_picture); - set_profile_save = (Button) findViewById(R.id.set_profile_save); - set_header_picture_overlay = (TextView) findViewById(R.id.set_header_picture_overlay); + set_profile_name = findViewById(R.id.set_profile_name); + set_profile_description = findViewById(R.id.set_profile_description); + set_profile_picture = findViewById(R.id.set_profile_picture); + set_header_picture = findViewById(R.id.set_header_picture); + set_change_profile_picture = findViewById(R.id.set_change_profile_picture); + set_change_header_picture = findViewById(R.id.set_change_header_picture); + set_profile_save = findViewById(R.id.set_profile_save); + set_header_picture_overlay = findViewById(R.id.set_header_picture_overlay); set_profile_save.setEnabled(false); set_change_header_picture.setEnabled(false); @@ -315,10 +314,10 @@ public class EditProfileActivity extends AppCompatActivity implements OnRetrieve @SuppressLint("InflateParams") View dialogView = inflater.inflate(R.layout.dialog_profile, null); dialogBuilder.setView(dialogView); - ImageView back_ground_image = (ImageView) dialogView.findViewById(R.id.back_ground_image); - ImageView dialog_profile_picture = (ImageView) dialogView.findViewById(R.id.dialog_profile_picture); - TextView dialog_profile_name = (TextView) dialogView.findViewById(R.id.dialog_profile_name); - TextView dialog_profile_description = (TextView) dialogView.findViewById(R.id.dialog_profile_description); + ImageView back_ground_image = dialogView.findViewById(R.id.back_ground_image); + ImageView dialog_profile_picture = dialogView.findViewById(R.id.dialog_profile_picture); + TextView dialog_profile_name = dialogView.findViewById(R.id.dialog_profile_name); + TextView dialog_profile_description = dialogView.findViewById(R.id.dialog_profile_description); if( profile_username != null) dialog_profile_name.setText(profile_username); @@ -386,6 +385,7 @@ public class EditProfileActivity extends AppCompatActivity implements OnRetrieve return; } try { + //noinspection ConstantConditions InputStream inputStream = getApplicationContext().getContentResolver().openInputStream(data.getData()); BufferedInputStream bufferedInputStream; if (inputStream != null) { @@ -412,7 +412,7 @@ public class EditProfileActivity extends AppCompatActivity implements OnRetrieve return; } try { - InputStream inputStream = getApplicationContext().getContentResolver().openInputStream(data.getData()); + @SuppressWarnings("ConstantConditions") InputStream inputStream = getApplicationContext().getContentResolver().openInputStream(data.getData()); BufferedInputStream bufferedInputStream; if (inputStream != null) { bufferedInputStream = new BufferedInputStream(inputStream); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/HashTagActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/HashTagActivity.java index 3ab4c8722..395217000 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/HashTagActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/HashTagActivity.java @@ -25,8 +25,6 @@ import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.MenuItem; import android.view.View; -import android.widget.AbsListView; -import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Toast; @@ -37,7 +35,6 @@ import fr.gouv.etalab.mastodon.asynctasks.RetrieveFeedsAsyncTask; import fr.gouv.etalab.mastodon.client.APIResponse; import fr.gouv.etalab.mastodon.client.Entities.Status; import fr.gouv.etalab.mastodon.drawers.StatusListAdapter; -import fr.gouv.etalab.mastodon.fragments.DisplayStatusFragment; import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveFeedsInterface; import mastodon.etalab.gouv.fr.mastodon.R; @@ -90,17 +87,17 @@ public class HashTagActivity extends AppCompatActivity implements OnRetrieveFeed flag_loading = true; firstLoad = true; boolean isOnWifi = Helper.isOnWIFI(getApplicationContext()); - swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeContainer); + swipeRefreshLayout = findViewById(R.id.swipeContainer); int behaviorWithAttachments = sharedpreferences.getInt(Helper.SET_ATTACHMENT_ACTION, Helper.ATTACHMENT_ALWAYS); - final RecyclerView lv_status = (RecyclerView) findViewById(R.id.lv_status); + final RecyclerView lv_status = findViewById(R.id.lv_status); tootsPerPage = sharedpreferences.getInt(Helper.SET_TOOTS_PER_PAGE, 40); - mainLoader = (RelativeLayout) findViewById(R.id.loader); - nextElementLoader = (RelativeLayout) findViewById(R.id.loading_next_status); - textviewNoAction = (RelativeLayout) findViewById(R.id.no_action); + mainLoader = findViewById(R.id.loader); + nextElementLoader = findViewById(R.id.loading_next_status); + textviewNoAction = findViewById(R.id.no_action); mainLoader.setVisibility(View.VISIBLE); nextElementLoader.setVisibility(View.GONE); int positionSpinnerTrans = (sharedpreferences.getInt(Helper.SET_TRANSLATOR, Helper.TRANS_YANDEX)); @@ -187,9 +184,7 @@ public class HashTagActivity extends AppCompatActivity implements OnRetrieveFeed else max_id = null; if( statuses != null) { - for(Status tmpStatus: statuses){ - this.statuses.add(tmpStatus); - } + this.statuses.addAll(statuses); statusListAdapter.notifyDataSetChanged(); } swipeRefreshLayout.setRefreshing(false); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/InstanceActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/InstanceActivity.java index bb1d3b9c4..e08ad2f77 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/InstanceActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/InstanceActivity.java @@ -64,8 +64,8 @@ public class InstanceActivity extends AppCompatActivity implements OnRetrieveIns getSupportActionBar().setDisplayHomeAsUpEnabled(true); setContentView(R.layout.activity_instance); - instance_container = (LinearLayout) findViewById(R.id.instance_container); - loader = (RelativeLayout) findViewById(R.id.loader); + instance_container = findViewById(R.id.instance_container); + loader = findViewById(R.id.loader); instance_container.setVisibility(View.GONE); loader.setVisibility(View.VISIBLE); setTitle(getString(R.string.action_about_instance)); @@ -94,11 +94,11 @@ public class InstanceActivity extends AppCompatActivity implements OnRetrieveIns return; } final Instance instance = apiResponse.getInstance(); - TextView instance_title = (TextView) findViewById(R.id.instance_title); - TextView instance_description = (TextView) findViewById(R.id.instance_description); - TextView instance_version = (TextView) findViewById(R.id.instance_version); - TextView instance_uri = (TextView) findViewById(R.id.instance_uri); - FloatingActionButton instance_contact = (FloatingActionButton) findViewById(R.id.instance_contact); + TextView instance_title = findViewById(R.id.instance_title); + TextView instance_description = findViewById(R.id.instance_description); + TextView instance_version = findViewById(R.id.instance_version); + TextView instance_uri = findViewById(R.id.instance_uri); + FloatingActionButton instance_contact = findViewById(R.id.instance_contact); instance_title.setText(instance.getTitle()); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/MediaActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/MediaActivity.java index 45f648772..1af17022e 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/MediaActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/MediaActivity.java @@ -119,13 +119,14 @@ public class MediaActivity extends AppCompatActivity { } setContentView(R.layout.activity_media); attachments = getIntent().getParcelableArrayListExtra("mediaArray"); - mediaPosition = getIntent().getExtras().getInt("position", 1); + if( getIntent().getExtras() != null) + mediaPosition = getIntent().getExtras().getInt("position", 1); if( attachments == null || attachments.size() == 0) finish(); if( getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); - RelativeLayout main_container_media = (RelativeLayout) findViewById(R.id.main_container_media); + RelativeLayout main_container_media = findViewById(R.id.main_container_media); if( theme == Helper.THEME_LIGHT){ main_container_media.setBackgroundResource(R.color.mastodonC2); }else { @@ -135,11 +136,11 @@ public class MediaActivity extends AppCompatActivity { changeDrawableColor(getApplicationContext(), R.drawable.ic_prev_pic,R.color.mastodonC4); canSwipe = true; - loader = (RelativeLayout) findViewById(R.id.loader); - imageView = (PhotoView) findViewById(R.id.media_picture); - videoView = (VideoView) findViewById(R.id.media_video); - prev = (ImageView) findViewById(R.id.media_prev); - next = (ImageView) findViewById(R.id.media_next); + loader = findViewById(R.id.loader); + imageView = findViewById(R.id.media_picture); + videoView = findViewById(R.id.media_video); + prev = findViewById(R.id.media_prev); + next = findViewById(R.id.media_next); prev.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -161,7 +162,7 @@ public class MediaActivity extends AppCompatActivity { } }); - progress = (TextView) findViewById(R.id.loader_progress); + progress = findViewById(R.id.loader_progress); setTitle(""); isHiding = false; @@ -399,7 +400,7 @@ public class MediaActivity extends AppCompatActivity { ActionBar actionBar = getSupportActionBar(); if( actionBar != null){ @SuppressLint("InflateParams") View picture_actionbar = mInflater.inflate(R.layout.picture_actionbar, null); - TextView picture_actionbar_title = (TextView) picture_actionbar.findViewById(R.id.picture_actionbar); + TextView picture_actionbar_title = picture_actionbar.findViewById(R.id.picture_actionbar); picture_actionbar_title.setText(filename); actionBar.setCustomView(picture_actionbar); actionBar.setDisplayShowCustomEnabled(true); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java index f1949ef8c..b3904fbe5 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java @@ -128,6 +128,7 @@ public class RemoteFollowActivity extends AppCompatActivity implements OnRetriev ActionBar actionBar = getSupportActionBar(); if( actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(android.content.Context.LAYOUT_INFLATER_SERVICE); + assert inflater != null; @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.conversation_action_bar, null); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); @@ -253,6 +254,7 @@ public class RemoteFollowActivity extends AppCompatActivity implements OnRetriev screen_name = screen_name.substring(1); new RetrieveRemoteAccountsAsyncTask(getApplicationContext(), screen_name, instance_name, RemoteFollowActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); + assert imm != null; imm.hideSoftInputFromWindow(rf_search.getWindowToken(), 0); } }); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/SearchResultActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/SearchResultActivity.java index 5492a5787..a897b8a4f 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/SearchResultActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/SearchResultActivity.java @@ -61,8 +61,8 @@ public class SearchResultActivity extends AppCompatActivity implements OnRetriev } setContentView(R.layout.activity_search_result); - loader = (RelativeLayout) findViewById(R.id.loader); - lv_search = (ListView) findViewById(R.id.lv_search); + loader = findViewById(R.id.loader); + lv_search = findViewById(R.id.lv_search); Bundle b = getIntent().getExtras(); if(b != null){ @@ -107,7 +107,7 @@ public class SearchResultActivity extends AppCompatActivity implements OnRetriev return; } if( results == null || (results.getAccounts().size() == 0 && results.getStatuses().size() == 0 && results.getHashtags().size() == 0)){ - RelativeLayout no_result = (RelativeLayout) findViewById(R.id.no_result); + RelativeLayout no_result = findViewById(R.id.no_result); no_result.setVisibility(View.VISIBLE); return; } diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowAccountActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowAccountActivity.java index dbc2118de..19c1a5158 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowAccountActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowAccountActivity.java @@ -363,42 +363,40 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi }else { changeDrawableColor(getApplicationContext(), R.drawable.ic_action_lock_closed,R.color.mastodonC4); } - if( account!= null) { - String urlHeader = account.getHeader(); - if (urlHeader.startsWith("/")) { - urlHeader = "https://" + Helper.getLiveInstance(ShowAccountActivity.this) + account.getHeader(); - } - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && !urlHeader.contains("missing.png")) { + String urlHeader = account.getHeader(); + if (urlHeader.startsWith("/")) { + urlHeader = "https://" + Helper.getLiveInstance(ShowAccountActivity.this) + account.getHeader(); + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && !urlHeader.contains("missing.png")) { - DisplayImageOptions optionNew = new DisplayImageOptions.Builder().displayer(new SimpleBitmapDisplayer()).cacheInMemory(false) - .cacheOnDisk(true).resetViewBeforeLoading(true).build(); - imageLoader.loadImage(urlHeader, optionNew, new SimpleImageLoadingListener() { - @RequiresApi(Build.VERSION_CODES.JELLY_BEAN) - @Override - public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { - super.onLoadingComplete(imageUri, view, loadedImage); - ImageView banner_pp = findViewById(R.id.banner_pp); - Bitmap workingBitmap = Bitmap.createBitmap(loadedImage); - Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true); - Canvas canvas = new Canvas(mutableBitmap); - Paint p = new Paint(Color.BLACK); - ColorFilter filter = new LightingColorFilter(0xFF7F7F7F, 0x00000000); - p.setColorFilter(filter); - canvas.drawBitmap(mutableBitmap, new Matrix(), p); - BitmapDrawable background = new BitmapDrawable(getResources(), mutableBitmap); - banner_pp.setImageDrawable(background); - } + DisplayImageOptions optionNew = new DisplayImageOptions.Builder().displayer(new SimpleBitmapDisplayer()).cacheInMemory(false) + .cacheOnDisk(true).resetViewBeforeLoading(true).build(); + imageLoader.loadImage(urlHeader, optionNew, new SimpleImageLoadingListener() { + @RequiresApi(Build.VERSION_CODES.JELLY_BEAN) + @Override + public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { + super.onLoadingComplete(imageUri, view, loadedImage); + ImageView banner_pp = findViewById(R.id.banner_pp); + Bitmap workingBitmap = Bitmap.createBitmap(loadedImage); + Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true); + Canvas canvas = new Canvas(mutableBitmap); + Paint p = new Paint(Color.BLACK); + ColorFilter filter = new LightingColorFilter(0xFF7F7F7F, 0x00000000); + p.setColorFilter(filter); + canvas.drawBitmap(mutableBitmap, new Matrix(), p); + BitmapDrawable background = new BitmapDrawable(getResources(), mutableBitmap); + banner_pp.setImageDrawable(background); + } - @Override - public void onLoadingFailed(java.lang.String imageUri, android.view.View view, FailReason failReason) { + @Override + public void onLoadingFailed(String imageUri, View view, FailReason failReason) { - } - }); - } + } + }); } //Redraws icon for locked accounts final float scale = getResources().getDisplayMetrics().density; - if( account != null && account.isLocked()){ + if(account.isLocked()){ Drawable img = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_action_lock_closed); img.setBounds(0,0,(int) (20 * scale + 0.5f),(int) (20 * scale + 0.5f)); account_dn.setCompoundDrawables( img, null, null, null); @@ -407,170 +405,160 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi } - if( account != null){ - TextView actionbar_title = findViewById(R.id.show_account_title); - if( account.getAcct() != null) - actionbar_title.setText(account.getAcct()); - pp_actionBar = findViewById(R.id.pp_actionBar); - String url = account.getAvatar(); - if( url.startsWith("/") ){ - url = "https://" + Helper.getLiveInstance(getApplicationContext()) + account.getAvatar(); + TextView actionbar_title = findViewById(R.id.show_account_title); + if( account.getAcct() != null) + actionbar_title.setText(account.getAcct()); + pp_actionBar = findViewById(R.id.pp_actionBar); + String url = account.getAvatar(); + if( url.startsWith("/") ){ + url = "https://" + Helper.getLiveInstance(getApplicationContext()) + account.getAvatar(); + } + DisplayImageOptions optionsPP = new DisplayImageOptions.Builder().displayer(new SimpleBitmapDisplayer()).cacheInMemory(false) + .cacheOnDisk(true).resetViewBeforeLoading(true).build(); + imageLoader.loadImage(url, optionsPP, new SimpleImageLoadingListener(){ + @Override + public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { + super.onLoadingComplete(imageUri, view, loadedImage); + BitmapDrawable ppDrawable = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(loadedImage, (int) Helper.convertDpToPixel(25, getApplicationContext()), (int) Helper.convertDpToPixel(25, getApplicationContext()), true)); + if( pp_actionBar != null){ + pp_actionBar.setImageDrawable(ppDrawable); + } } - DisplayImageOptions optionsPP = new DisplayImageOptions.Builder().displayer(new SimpleBitmapDisplayer()).cacheInMemory(false) - .cacheOnDisk(true).resetViewBeforeLoading(true).build(); - imageLoader.loadImage(url, optionsPP, new SimpleImageLoadingListener(){ - @Override - public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { - super.onLoadingComplete(imageUri, view, loadedImage); - BitmapDrawable ppDrawable = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(loadedImage, (int) Helper.convertDpToPixel(25, getApplicationContext()), (int) Helper.convertDpToPixel(25, getApplicationContext()), true)); - if( pp_actionBar != null){ - pp_actionBar.setImageDrawable(ppDrawable); + @Override + public void onLoadingFailed(String imageUri, View view, FailReason failReason){ + + }}); + final AppBarLayout appBar = findViewById(R.id.appBar); + maxScrollSize = appBar.getTotalScrollRange(); + + + appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { + @Override + public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { + LinearLayout toolbarContent = findViewById(R.id.toolbar_content); + if( toolbarContent != null) { + if (Math.abs(verticalOffset) - appBar.getTotalScrollRange() == 0) { + if (toolbarContent.getVisibility() == View.GONE) + toolbarContent.setVisibility(View.VISIBLE); + } else { + if (toolbarContent.getVisibility() == View.VISIBLE) + toolbarContent.setVisibility(View.GONE); } } + if (maxScrollSize == 0) + maxScrollSize = appBarLayout.getTotalScrollRange(); + + int percentage = (Math.abs(verticalOffset)) * 100 / maxScrollSize; + + if (percentage >= 40 && avatarShown) { + avatarShown = false; + + account_pp.animate() + .scaleY(0).scaleX(0) + .setDuration(400) + .start(); + } + if (percentage <= 40 && !avatarShown) { + avatarShown = true; + account_pp.animate() + .scaleY(1).scaleX(1) + .start(); + } + } + }); + account_dn.setText(Helper.shortnameToUnicode(account.getDisplay_name(), true)); + account_un.setText(String.format("@%s", account.getAcct())); + SpannableString spannableString = Helper.clickableElementsDescription(ShowAccountActivity.this, account.getNote()); + account_note.setText(spannableString, TextView.BufferType.SPANNABLE); + account_note.setMovementMethod(LinkMovementMethod.getInstance()); + if (tabLayout.getTabAt(0) != null && tabLayout.getTabAt(1) != null && tabLayout.getTabAt(2) != null) { + //noinspection ConstantConditions + tabLayout.getTabAt(0).setText(getString(R.string.status_cnt, account.getStatuses_count())); + //noinspection ConstantConditions + tabLayout.getTabAt(1).setText(getString(R.string.following_cnt, account.getFollowing_count())); + //noinspection ConstantConditions + tabLayout.getTabAt(2).setText(getString(R.string.followers_cnt, account.getFollowers_count())); + + //Allows to filter by long click + final LinearLayout tabStrip = (LinearLayout) tabLayout.getChildAt(0); + tabStrip.getChildAt(0).setOnLongClickListener(new View.OnLongClickListener() { @Override - public void onLoadingFailed(java.lang.String imageUri, android.view.View view, FailReason failReason){ + public boolean onLongClick(View v) { + PopupMenu popup = new PopupMenu(ShowAccountActivity.this, tabStrip.getChildAt(0)); + popup.getMenuInflater() + .inflate(R.menu.option_filter_toots_account, popup.getMenu()); + Menu menu = popup.getMenu(); - }}); - final AppBarLayout appBar = findViewById(R.id.appBar); - maxScrollSize = appBar.getTotalScrollRange(); + if( !Helper.canPin || !accountId.equals(userId)) { + popup.getMenu().findItem(R.id.action_show_pinned).setVisible(false); + } + final MenuItem itemShowPined = menu.findItem(R.id.action_show_pinned); + final MenuItem itemShowMedia = menu.findItem(R.id.action_show_media); - - appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() { - @Override - public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) { - LinearLayout toolbarContent = findViewById(R.id.toolbar_content); - if( toolbarContent != null) { - if (Math.abs(verticalOffset) - appBar.getTotalScrollRange() == 0) { - if (toolbarContent.getVisibility() == View.GONE) - toolbarContent.setVisibility(View.VISIBLE); - } else { - if (toolbarContent.getVisibility() == View.VISIBLE) - toolbarContent.setVisibility(View.GONE); + itemShowMedia.setChecked(showMediaOnly); + itemShowPined.setChecked(showPinned); + popup.setOnDismissListener(new PopupMenu.OnDismissListener() { + @Override + public void onDismiss(PopupMenu menu) { + if( displayStatusFragment != null) + displayStatusFragment.refreshFilter(); } - } - if (maxScrollSize == 0) - maxScrollSize = appBarLayout.getTotalScrollRange(); + }); + popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { + public boolean onMenuItemClick(MenuItem item) { + item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW); + item.setActionView(new View(getApplicationContext())); + item.setOnActionExpandListener(new MenuItem.OnActionExpandListener() { + @Override + public boolean onMenuItemActionExpand(MenuItem item) { + return false; + } - int percentage = (Math.abs(verticalOffset)) * 100 / maxScrollSize; - - if (percentage >= 40 && avatarShown) { - avatarShown = false; - - account_pp.animate() - .scaleY(0).scaleX(0) - .setDuration(400) - .start(); - } - if (percentage <= 40 && !avatarShown) { - avatarShown = true; - account_pp.animate() - .scaleY(1).scaleX(1) - .start(); - } + @Override + public boolean onMenuItemActionCollapse(MenuItem item) { + return false; + } + }); + switch (item.getItemId()) { + case R.id.action_show_pinned: + showPinned = !showPinned; + if( tabLayout.getTabAt(0) != null) + //noinspection ConstantConditions + tabLayout.getTabAt(0).select(); + PagerAdapter mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager()); + mPager.setAdapter(mPagerAdapter); + break; + case R.id.action_show_media: + showMediaOnly = !showMediaOnly; + if( tabLayout.getTabAt(0) != null) + //noinspection ConstantConditions + tabLayout.getTabAt(0).select(); + mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager()); + mPager.setAdapter(mPagerAdapter); + break; + } + itemShowMedia.setChecked(showMediaOnly); + itemShowPined.setChecked(showPinned); + return false; + } + }); + popup.show(); + return true; } }); - }else { - if( account != null && account.getAcct() != null) - setTitle(account.getAcct()); - } - if( account != null){ - account_dn.setText(Helper.shortnameToUnicode(account.getDisplay_name(), true)); - account_un.setText(String.format("@%s", account.getAcct())); - SpannableString spannableString = Helper.clickableElementsDescription(ShowAccountActivity.this, account.getNote()); - account_note.setText(spannableString, TextView.BufferType.SPANNABLE); - account_note.setMovementMethod(LinkMovementMethod.getInstance()); - if (tabLayout.getTabAt(0) != null && tabLayout.getTabAt(1) != null && tabLayout.getTabAt(2) != null) { - //noinspection ConstantConditions - tabLayout.getTabAt(0).setText(getString(R.string.status_cnt, account.getStatuses_count())); - //noinspection ConstantConditions - tabLayout.getTabAt(1).setText(getString(R.string.following_cnt, account.getFollowing_count())); - //noinspection ConstantConditions - tabLayout.getTabAt(2).setText(getString(R.string.followers_cnt, account.getFollowers_count())); - - //Allows to filter by long click - final LinearLayout tabStrip = (LinearLayout) tabLayout.getChildAt(0); - tabStrip.getChildAt(0).setOnLongClickListener(new View.OnLongClickListener() { - @Override - public boolean onLongClick(View v) { - PopupMenu popup = new PopupMenu(ShowAccountActivity.this, tabStrip.getChildAt(0)); - popup.getMenuInflater() - .inflate(R.menu.option_filter_toots_account, popup.getMenu()); - Menu menu = popup.getMenu(); - - if( !Helper.canPin || !accountId.equals(userId)) { - popup.getMenu().findItem(R.id.action_show_pinned).setVisible(false); - } - final MenuItem itemShowPined = menu.findItem(R.id.action_show_pinned); - final MenuItem itemShowMedia = menu.findItem(R.id.action_show_media); - - itemShowMedia.setChecked(showMediaOnly); - itemShowPined.setChecked(showPinned); - popup.setOnDismissListener(new PopupMenu.OnDismissListener() { - @Override - public void onDismiss(PopupMenu menu) { - if( displayStatusFragment != null) - displayStatusFragment.refreshFilter(); - } - }); - popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { - public boolean onMenuItemClick(MenuItem item) { - item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW); - item.setActionView(new View(getApplicationContext())); - item.setOnActionExpandListener(new MenuItem.OnActionExpandListener() { - @Override - public boolean onMenuItemActionExpand(MenuItem item) { - return false; - } - - @Override - public boolean onMenuItemActionCollapse(MenuItem item) { - return false; - } - }); - switch (item.getItemId()) { - case R.id.action_show_pinned: - showPinned = !showPinned; - if( tabLayout.getTabAt(0) != null) - //noinspection ConstantConditions - tabLayout.getTabAt(0).select(); - PagerAdapter mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager()); - mPager.setAdapter(mPagerAdapter); - break; - case R.id.action_show_media: - showMediaOnly = !showMediaOnly; - if( tabLayout.getTabAt(0) != null) - //noinspection ConstantConditions - tabLayout.getTabAt(0).select(); - mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager()); - mPager.setAdapter(mPagerAdapter); - break; - } - itemShowMedia.setChecked(showMediaOnly); - itemShowPined.setChecked(showPinned); - return false; - } - }); - popup.show(); - return true; - } - }); - - - } - - imageLoader.displayImage(account.getAvatar(), account_pp, options); - } + + imageLoader.displayImage(account.getAvatar(), account_pp, options); + + } @Override public void onRetrieveFeedsAccount(List statuses) { if( statuses != null) { - for(Status tmpStatus: statuses){ - this.statuses.add(tmpStatus); - } + this.statuses.addAll(statuses); statusListAdapter.notifyDataSetChanged(); } } @@ -588,10 +576,7 @@ public class ShowAccountActivity extends AppCompatActivity implements OnPostActi pins = apiResponse.getStatuses(); if (pins != null && pins.size() > 0) { if( pins.get(0).isPinned()) { - - for (Status pin : pins) { - this.statuses.add(pin); - } + this.statuses.addAll(pins); //noinspection ConstantConditions tabLayout.getTabAt(3).setText(getString(R.string.pins_cnt, pins.size())); statusListAdapter.notifyDataSetChanged(); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowConversationActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowConversationActivity.java index 4d8dbc115..71708ae0f 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowConversationActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/ShowConversationActivity.java @@ -15,6 +15,7 @@ package fr.gouv.etalab.mastodon.activities; +import android.annotation.SuppressLint; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.graphics.Bitmap; @@ -33,7 +34,6 @@ import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; -import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; @@ -98,7 +98,8 @@ public class ShowConversationActivity extends AppCompatActivity implements OnRet ActionBar actionBar = getSupportActionBar(); if( actionBar != null) { LayoutInflater inflater = (LayoutInflater) this.getSystemService(android.content.Context.LAYOUT_INFLATER_SERVICE); - View view = inflater.inflate(R.layout.conversation_action_bar, null); + assert inflater != null; + @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.conversation_action_bar, null); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); TextView title = actionBar.getCustomView().findViewById(R.id.toolbar_title); @@ -173,7 +174,7 @@ public class ShowConversationActivity extends AppCompatActivity implements OnRet new RetrieveFeedsAsyncTask(getApplicationContext(), RetrieveFeedsAsyncTask.Type.ONESTATUS, statusId,null, false,false, ShowConversationActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } }); - lv_status = (RecyclerView) findViewById(R.id.lv_status); + lv_status = findViewById(R.id.lv_status); final LinearLayoutManager mLayoutManager; mLayoutManager = new LinearLayoutManager(this); lv_status.setLayoutManager(mLayoutManager); @@ -182,7 +183,6 @@ public class ShowConversationActivity extends AppCompatActivity implements OnRet public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == android.view.MotionEvent.ACTION_UP) { int visibleItemCount = mLayoutManager.getChildCount(); - int totalItemCount = mLayoutManager.getItemCount(); int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition(); if (firstVisibleItem + visibleItemCount == lv_status.getAdapter().getItemCount() -1 && firstVisibleItem > 0 && lv_status.getChildAt(lv_status.getChildCount() - 1).getBottom() <= lv_status.getHeight()) { diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java index 4f704f9cd..049446e79 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/TootActivity.java @@ -193,6 +193,7 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc ActionBar actionBar = getSupportActionBar(); if( actionBar != null ){ LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + assert inflater != null; @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.toot_action_bar, null); actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); @@ -202,6 +203,7 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc @Override public void onClick(View v) { InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); + assert inputMethodManager != null; inputMethodManager.hideSoftInputFromWindow(toot_content.getWindowToken(), 0); finish(); } @@ -550,6 +552,18 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc String patternTag = "^(.|\\s)*(\\#([\\w-]{2,}))$"; final Pattern tPattern = Pattern.compile(patternTag); + toot_cw_content.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) {} + @Override + public void afterTextChanged(Editable s) { + int totalChar = toot_cw_content.length() + toot_content.length(); + toot_space_left.setText(String.valueOf(totalChar)); + } + }); + toot_content.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { @@ -607,32 +621,8 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc toot_space_left.setText(String.valueOf(totalChar)); } }); - //Allow scroll of the EditText though it's embedded in a scrollview - toot_content.setOnTouchListener(new View.OnTouchListener() { - @Override - public boolean onTouch(View v, MotionEvent event) { - if (v.getId() == R.id.toot_content) { - v.getParent().requestDisallowInterceptTouchEvent(true); - switch (event.getAction() & MotionEvent.ACTION_MASK) { - case MotionEvent.ACTION_UP: - v.getParent().requestDisallowInterceptTouchEvent(false); - break; - } - } - return false; - } - }); - toot_cw_content.addTextChangedListener(new TextWatcher() { - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) {} - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) {} - @Override - public void afterTextChanged(Editable s) { - int totalChar = toot_cw_content.length() + toot_content.length(); - toot_space_left.setText(String.valueOf(totalChar)); - } - }); + + if( restored != -1 ){ restoreToot(restored); } @@ -720,6 +710,7 @@ public class TootActivity extends AppCompatActivity implements OnRetrieveSearcAc return; } try { + //noinspection ConstantConditions InputStream inputStream = getContentResolver().openInputStream(data.getData()); toot_picture_container.setVisibility(View.VISIBLE); loading_picture.setVisibility(View.VISIBLE); diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewActivity.java index 985ebb20b..a15fba197 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewActivity.java @@ -76,8 +76,8 @@ public class WebviewActivity extends AppCompatActivity { webView = Helper.initializeWebview(WebviewActivity.this, R.id.webview); setTitle(""); - FrameLayout webview_container = (FrameLayout) findViewById(R.id.webview_container); - final ViewGroup videoLayout = (ViewGroup) findViewById(R.id.videoLayout); // Your own view, read class comments + FrameLayout webview_container = findViewById(R.id.webview_container); + final ViewGroup videoLayout = findViewById(R.id.videoLayout); // Your own view, read class comments MastalabWebChromeClient mastalabWebChromeClient = new MastalabWebChromeClient(WebviewActivity.this, webView, webview_container, videoLayout); mastalabWebChromeClient.setOnToggledFullscreen(new MastalabWebChromeClient.ToggledFullscreenCallback() { diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewConnectActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewConnectActivity.java index 0a0f5046f..18f115dab 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewConnectActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/WebviewConnectActivity.java @@ -75,9 +75,9 @@ public class WebviewConnectActivity extends AppCompatActivity { clientId = sharedpreferences.getString(Helper.CLIENT_ID, null); clientSecret = sharedpreferences.getString(Helper.CLIENT_SECRET, null); - webView = (WebView) findViewById(R.id.webviewConnect); + webView = findViewById(R.id.webviewConnect); clearCookies(getApplicationContext()); - final ProgressBar pbar = (ProgressBar) findViewById(R.id.progress_bar); + final ProgressBar pbar = findViewById(R.id.progress_bar); webView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int progress) { From fb9e1e25214e0cfa648bd25ff28b85d9f1fb9139 Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 15:55:10 +0200 Subject: [PATCH 44/46] Cleans code in Webview --- .../mastodon/webview/MastalabWebChromeClient.java | 11 +++++++---- .../mastodon/webview/MastalabWebViewClient.java | 5 +++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/webview/MastalabWebChromeClient.java b/app/src/main/java/fr/gouv/etalab/mastodon/webview/MastalabWebChromeClient.java index 84d3dc6f0..dabd78c3a 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/webview/MastalabWebChromeClient.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/webview/MastalabWebChromeClient.java @@ -13,6 +13,7 @@ package fr.gouv.etalab.mastodon.webview; * * You should have received a copy of the GNU General Public License along with Mastalab; if not, * see . */ +import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.Bitmap; import android.media.MediaPlayer; @@ -59,7 +60,7 @@ public class MastalabWebChromeClient extends WebChromeClient implements MediaPla this.activity = activity; this.isVideoFullscreen = false; this.webView = webView; - this.pbar = (ProgressBar) activity.findViewById(R.id.progress_bar); + this.pbar = activity.findViewById(R.id.progress_bar); this.activityNonVideoView = activityNonVideoView; this.activityVideoView = activityVideoView; } @@ -84,10 +85,10 @@ public class MastalabWebChromeClient extends WebChromeClient implements MediaPla LayoutInflater mInflater = LayoutInflater.from(activity); ActionBar actionBar = ((AppCompatActivity) activity).getSupportActionBar(); if( actionBar != null){ - View webview_actionbar = mInflater.inflate(R.layout.webview_actionbar, null); - TextView webview_title = (TextView) webview_actionbar.findViewById(R.id.webview_title); + @SuppressLint("InflateParams") View webview_actionbar = mInflater.inflate(R.layout.webview_actionbar, null); + TextView webview_title = webview_actionbar.findViewById(R.id.webview_title); webview_title.setText(view.getTitle()); - ImageView webview_favicon = (ImageView) webview_actionbar.findViewById(R.id.webview_favicon); + ImageView webview_favicon = webview_actionbar.findViewById(R.id.webview_favicon); if( icon != null) webview_favicon.setImageBitmap(icon); actionBar.setCustomView(webview_actionbar); @@ -113,6 +114,7 @@ public class MastalabWebChromeClient extends WebChromeClient implements MediaPla public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) { if (view instanceof FrameLayout) { if( ((AppCompatActivity) activity).getSupportActionBar() != null) + //noinspection ConstantConditions ((AppCompatActivity) activity).getSupportActionBar().hide(); // A video wants to be shown FrameLayout frameLayout = (FrameLayout) view; @@ -176,6 +178,7 @@ public class MastalabWebChromeClient extends WebChromeClient implements MediaPla @Override public void onHideCustomView() { if( ((AppCompatActivity) activity).getSupportActionBar() != null) + //noinspection ConstantConditions ((AppCompatActivity) activity).getSupportActionBar().show(); // This method should be manually called on video end in all cases because it's not always called automatically. // This method must be manually called on back key press (from this class' onBackPressed() method). diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/webview/MastalabWebViewClient.java b/app/src/main/java/fr/gouv/etalab/mastodon/webview/MastalabWebViewClient.java index 01052eb6e..dced8229c 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/webview/MastalabWebViewClient.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/webview/MastalabWebViewClient.java @@ -13,6 +13,7 @@ package fr.gouv.etalab.mastodon.webview; * * You should have received a copy of the GNU General Public License along with Mastalab; if not, * see . */ +import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.Bitmap; import android.support.v7.app.ActionBar; @@ -51,8 +52,8 @@ public class MastalabWebViewClient extends WebViewClient { ActionBar actionBar = ((AppCompatActivity) activity).getSupportActionBar(); LayoutInflater mInflater = LayoutInflater.from(activity); if( actionBar != null){ - View webview_actionbar = mInflater.inflate(R.layout.webview_actionbar, null); - TextView webview_title = (TextView) webview_actionbar.findViewById(R.id.webview_title); + @SuppressLint("InflateParams") View webview_actionbar = mInflater.inflate(R.layout.webview_actionbar, null); + TextView webview_title = webview_actionbar.findViewById(R.id.webview_title); webview_title.setText(url); actionBar.setCustomView(webview_actionbar); actionBar.setDisplayShowCustomEnabled(true); From 89562d900d01f1f587d14fdc2206081c75b88cd3 Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 16:00:54 +0200 Subject: [PATCH 45/46] Adds description to media --- .../gouv/etalab/mastodon/helper/Helper.java | 30 +++++-------------- 1 file changed, 7 insertions(+), 23 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java b/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java index 1c50fc958..c57764ba8 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/helper/Helper.java @@ -58,7 +58,6 @@ import android.support.design.widget.NavigationView; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v4.content.ContextCompat; -import android.support.v7.widget.RecyclerView; import android.text.Html; import android.text.Spannable; import android.text.SpannableString; @@ -80,7 +79,6 @@ import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.ImageView; import android.widget.LinearLayout; -import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; @@ -575,6 +573,7 @@ public class Helper { request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); DownloadManager dm = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE); + assert dm != null; dm.enqueue(request); dialog.dismiss(); } @@ -750,8 +749,10 @@ public class Helper { */ public static void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); + //noinspection TryFinallyCanBeTryWithResources try { OutputStream out = new FileOutputStream(dst); + //noinspection TryFinallyCanBeTryWithResources try { byte[] buf = new byte[1024]; int len; @@ -972,7 +973,7 @@ public class Helper { @SuppressWarnings("SameParameterValue") - public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int roundPixelSize) { + private static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int roundPixelSize) { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final Paint paint = new Paint(); @@ -1147,6 +1148,7 @@ public class Helper { * @param mentions List * @return TextView */ + @SuppressWarnings("SameParameterValue") public static SpannableString clickableElements(final Context context, String fullContent, List mentions, final List emojis, final int position, boolean useHTML, final OnRetrieveEmojiInterface listener) { final SpannableString spannableString; @@ -1418,9 +1420,9 @@ public class Helper { // Create Hex String StringBuilder hexString = new StringBuilder(); for (byte aMessageDigest : messageDigest) { - String h = Integer.toHexString(0xFF & aMessageDigest); + StringBuilder h = new StringBuilder(Integer.toHexString(0xFF & aMessageDigest)); while (h.length() < 2) - h = "0" + h; + h.insert(0, "0"); hexString.append(h); } return hexString.toString(); @@ -1589,24 +1591,6 @@ public class Helper { } } - /** - * Returns true if a ListView is at its top position - * @param listView ListView - * @return boolean - */ - public static boolean listIsAtTop(RecyclerView listView) { - return listView.getChildCount() == 0 || listView.getChildAt(0).getTop() == 0; - } - - /** - * Returns true if a ListView is at its top position - * @param listView ListView - * @return boolean - */ - public static boolean listIsAtTop(ListView listView) { - return listView.getChildCount() == 0 || listView.getChildAt(0).getTop() == 0; - } - /** * Changes the menu layout From f9e3584b97ede2ca8fb1a129645a7ff2e366347b Mon Sep 17 00:00:00 2001 From: stom79 Date: Fri, 27 Oct 2017 16:35:01 +0200 Subject: [PATCH 46/46] Fixes a bug with remote follows --- .../mastodon/activities/RemoteFollowActivity.java | 10 ++++------ .../main/res/layout-sw600dp/activity_remote_follow.xml | 2 +- app/src/main/res/layout/activity_remote_follow.xml | 2 +- 3 files changed, 6 insertions(+), 8 deletions(-) diff --git a/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java b/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java index b3904fbe5..1a463475a 100644 --- a/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java +++ b/app/src/main/java/fr/gouv/etalab/mastodon/activities/RemoteFollowActivity.java @@ -28,7 +28,6 @@ import android.support.design.widget.FloatingActionButton; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; @@ -65,7 +64,6 @@ import java.util.List; import cz.msebera.android.httpclient.Header; import fr.gouv.etalab.mastodon.asynctasks.PostActionAsyncTask; -import fr.gouv.etalab.mastodon.asynctasks.RetrieveAccountsAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.RetrieveRelationshipAsyncTask; import fr.gouv.etalab.mastodon.asynctasks.RetrieveRemoteAccountsAsyncTask; import fr.gouv.etalab.mastodon.client.API; @@ -75,7 +73,8 @@ import fr.gouv.etalab.mastodon.client.Entities.Relationship; import fr.gouv.etalab.mastodon.client.Entities.Results; import fr.gouv.etalab.mastodon.client.KinrarClient; import fr.gouv.etalab.mastodon.client.PatchBaseImageDownloader; -import fr.gouv.etalab.mastodon.drawers.AccountsListAdapter; +import fr.gouv.etalab.mastodon.drawers.AccountSearchDevAdapter; +import fr.gouv.etalab.mastodon.helper.ExpandableHeightListView; import fr.gouv.etalab.mastodon.helper.Helper; import fr.gouv.etalab.mastodon.interfaces.OnPostActionInterface; import fr.gouv.etalab.mastodon.interfaces.OnRetrieveRelationshipInterface; @@ -98,7 +97,7 @@ public class RemoteFollowActivity extends AppCompatActivity implements OnRetriev private EditText rf_username; private TextView rf_no_result; private Button rf_search; - private RecyclerView lv_account; + private ExpandableHeightListView lv_account; private RelativeLayout loader; private boolean isLoadingInstance; private String instance_name, screen_name; @@ -289,8 +288,7 @@ public class RemoteFollowActivity extends AppCompatActivity implements OnRetriev if( accounts != null && accounts.size() > 0){ account = accounts.get(0); selectedAccount.add(account); - String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null); - AccountsListAdapter accountSearchWebAdapter = new AccountsListAdapter(RemoteFollowActivity.this, RetrieveAccountsAsyncTask.Type.FOLLOWERS, userId, selectedAccount); + AccountSearchDevAdapter accountSearchWebAdapter = new AccountSearchDevAdapter(RemoteFollowActivity.this, selectedAccount); lv_account.setAdapter(accountSearchWebAdapter); lv_account.setVisibility(View.VISIBLE); new RetrieveRelationshipAsyncTask(getApplicationContext(), account.getId(),RemoteFollowActivity.this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); diff --git a/app/src/main/res/layout-sw600dp/activity_remote_follow.xml b/app/src/main/res/layout-sw600dp/activity_remote_follow.xml index 28c77e808..ed2b95f1a 100644 --- a/app/src/main/res/layout-sw600dp/activity_remote_follow.xml +++ b/app/src/main/res/layout-sw600dp/activity_remote_follow.xml @@ -71,7 +71,7 @@ android:text="@string/action_search" /> - -