Commit 3449c40a authored by Varun Patil's avatar Varun Patil Committed by GitHub

Merge pull request #270 from wncc/codacy

Reduce technical debt, fix some issues
parents 3735fc4f c1756dfd
......@@ -2,7 +2,6 @@ package app.insti;
public class Constants {
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
public static final int MY_PERMISSIONS_REQUEST_ACCESS_LOCATION = 2;
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 3;
public static final int RESULT_LOAD_IMAGE = 11;
public static final int REQUEST_CAMERA_INT_ID = 101;
......
package app.insti;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by mrunz on 6/7/17.
*/
public class PeopleSuggestionAdapter extends BaseAdapter implements Filterable {
List mData;
List mStringFilterList;
ValueFilter valueFilter;
private LayoutInflater inflater;
public PeopleSuggestionAdapter(List cancel_type) {
mData = cancel_type;
mStringFilterList = cancel_type;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, final ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) parent.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
View view = inflater.inflate(R.layout.ppl_search_suggestion_item_view, parent, false);
TextView tv_suggestion = (TextView) view.findViewById(R.id.suggestion_item);
tv_suggestion.setText(mData.get(position).toString());
return view;
}
@Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
List filterList = new ArrayList();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ((mStringFilterList.get(i).toString().toUpperCase()).contains(constraint.toString().toUpperCase())) {
filterList.add(mStringFilterList.get(i));
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
mData = (List) results.values;
notifyDataSetChanged();
}
}
}
\ No newline at end of file
......@@ -88,8 +88,8 @@ public final class Utils {
public static final void updateFragment(Fragment fragment, FragmentActivity fragmentActivity) {
FragmentTransaction ft = fragmentActivity.getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_up, R.anim.fade_out, R.anim.fade_in, R.anim.slide_out_down);
ft.replace(R.id.framelayout_for_fragment, fragment, fragment.getTag());
ft.addToBackStack(fragment.getTag());
ft.replace(R.id.framelayout_for_fragment, fragment, getTag(fragment));
ft.addToBackStack(getTag(fragment));
ft.commit();
}
......@@ -141,8 +141,8 @@ public final class Utils {
}
/* Update the fragment */
ft.replace(R.id.framelayout_for_fragment, fragment, fragment.getTag())
.addToBackStack(fragment.getTag())
ft.replace(R.id.framelayout_for_fragment, fragment, getTag(fragment))
.addToBackStack(getTag(fragment))
.commit();
}
......@@ -247,8 +247,8 @@ public final class Utils {
FragmentManager fm = fragmentActivity.getSupportFragmentManager();
fm.popBackStack();
FragmentTransaction ft = fm.beginTransaction();
ft.addToBackStack(newFragment.getTag());
ft.replace(R.id.framelayout_for_fragment, newFragment, newFragment.getTag()).commit();
ft.addToBackStack(getTag(fragment));
ft.replace(R.id.framelayout_for_fragment, newFragment, getTag(fragment)).commit();
}
public static void setSelectedMenuItem(Activity activity, int id) {
......@@ -286,4 +286,12 @@ public final class Utils {
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();
}
public static String getTag(Fragment fragment) {
String TAG = fragment.getTag();
try {
TAG = (String) fragment.getClass().getField("TAG").get(fragment);
} catch (NoSuchFieldException | IllegalAccessException ignored) {}
return TAG;
}
}
......@@ -85,7 +85,6 @@ import static app.insti.Constants.DATA_TYPE_NEWS;
import static app.insti.Constants.DATA_TYPE_PT;
import static app.insti.Constants.DATA_TYPE_USER;
import static app.insti.Constants.FCM_BUNDLE_NOTIFICATION_ID;
import static app.insti.Constants.MY_PERMISSIONS_REQUEST_ACCESS_LOCATION;
import static app.insti.Constants.MY_PERMISSIONS_REQUEST_LOCATION;
import static app.insti.Constants.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE;
import static app.insti.Constants.RESULT_LOAD_IMAGE;
......@@ -616,7 +615,6 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
* Change the active fragment to the supplied one
*/
public void updateFragment(Fragment fragment) {
Log.d(TAG, "updateFragment: " + fragment.toString());
Bundle bundle = fragment.getArguments();
if (bundle == null) {
bundle = new Bundle();
......@@ -642,8 +640,8 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
transaction.setCustomAnimations(R.anim.slide_in_up, R.anim.fade_out, R.anim.fade_in, R.anim.slide_out_down);
}
transaction.replace(R.id.framelayout_for_fragment, fragment, fragment.getTag());
transaction.addToBackStack(fragment.getTag()).commit();
transaction.replace(R.id.framelayout_for_fragment, fragment, Utils.getTag(fragment));
transaction.addToBackStack(Utils.getTag(fragment)).commit();
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
......@@ -655,21 +653,20 @@ public class MainActivity extends AppCompatActivity implements NavigationView.On
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
return;
case MY_PERMISSIONS_REQUEST_ACCESS_LOCATION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
MapFragment.getMainActivity().setupGPS();
} else {
Toast toast = Toast.makeText(MainActivity.this, "Need Permission", Toast.LENGTH_SHORT);
toast.show();
}
break;
case MY_PERMISSIONS_REQUEST_LOCATION:
Log.i(TAG, "Permission request captured");
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission Granted");
FileComplaintFragment.getMainActivity().getMapReady();
// Map
MapFragment mapFragment = (MapFragment) getSupportFragmentManager().findFragmentByTag(MapFragment.TAG);
if (mapFragment != null && mapFragment.isVisible()) {
MapFragment.getMainActivity().setupGPS(true);
}
// File complaint
FileComplaintFragment fileComplaintFragment = (FileComplaintFragment) getSupportFragmentManager().findFragmentByTag(FileComplaintFragment.TAG);
if (fileComplaintFragment != null && fileComplaintFragment.isVisible()) {
FileComplaintFragment.getMainActivity().getMapReady();
}
} else {
Log.i(TAG, "Permission Cancelled");
Toast toast = Toast.makeText(MainActivity.this, "Need Permission", Toast.LENGTH_SHORT);
toast.show();
}
......
......@@ -74,7 +74,7 @@ public class MessMenuAdapter extends RecyclerView.Adapter<MessMenuAdapter.ViewHo
case 7:
return "Sunday";
default:
throw new RuntimeException("DayIndexOutOfBounds: " + day);
throw new IndexOutOfBoundsException("DayIndexOutOfBounds: " + day);
}
}
......
......@@ -29,7 +29,6 @@ public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> i
private final int VIEW_PROG = 0;
private List<NewsArticle> newsArticles;
private Context context;
private ItemClickListener itemClickListener;
public NewsAdapter(List<NewsArticle> newsArticles, ItemClickListener itemClickListener) {
......@@ -51,7 +50,7 @@ public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> i
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
final Context context = parent.getContext();
if (viewType == VIEW_ITEM) {
LayoutInflater inflater = LayoutInflater.from(context);
View postView = inflater.inflate(R.layout.news_article_card, parent, false);
......
......@@ -27,7 +27,6 @@ public class PlacementBlogAdapter extends RecyclerView.Adapter<RecyclerView.View
private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0;
private List<PlacementBlogPost> posts;
private Context context;
private ItemClickListener itemClickListener;
public PlacementBlogAdapter(List<PlacementBlogPost> posts, ItemClickListener itemClickListener) {
this.posts = posts;
......@@ -45,7 +44,7 @@ public class PlacementBlogAdapter extends RecyclerView.Adapter<RecyclerView.View
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
final Context context = parent.getContext();
if (viewType == VIEW_ITEM) {
LayoutInflater inflater = LayoutInflater.from(context);
View postView = inflater.inflate(R.layout.blog_post_card, parent, false);
......
......@@ -18,9 +18,10 @@ import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ServiceGenerator {
public static final String HEADER_CACHE_CONTROL = "Cache-Control";
public static final String HEADER_PRAGMA = "Pragma";
private static final String HEADER_CACHE_CONTROL = "Cache-Control";
private static final String HEADER_PRAGMA = "Pragma";
private static final String BASE_URL = "https://api.insti.app/api/";
public RetrofitInterface retrofitInterface;
private Context context;
......@@ -99,10 +100,9 @@ public class ServiceGenerator {
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
private Retrofit retrofit;
public RetrofitInterface retrofitInterface;
public ServiceGenerator(Context mContext) {
context = mContext;
final Retrofit retrofit;
retrofit = retrofitBuilder.client(
clientBuilder
.addInterceptor(provideOfflineCacheInterceptor)
......
package app.insti.api;
import android.content.Context;
import java.security.cert.CertificateException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
public class UnsafeOkHttpClient {
public static OkHttpClient getUnsafeOkHttpClient(Context context) {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
Cache cache = new Cache(context.getCacheDir(), 200000000);
builder.cache(cache);
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
OkHttpClient okHttpClient = builder.build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
......@@ -67,26 +67,8 @@ public class User implements CardInterface {
private String currentRole;
public User(@NonNull String userID, String userName, String userProfilePictureUrl, List<Event> userInterestedEvents, List<Event> userGoingEvents, String userEmail, String userRollNumber, String userContactNumber, Boolean showContactNumber, String userAbout, List<Body> userFollowedBodies, List<String> userFollowedBodiesID, List<Role> userRoles, List<Role> userInstituteRoles, List<Role> userFormerRoles, String userWebsiteURL, String userLDAPId, String hostel, String currentRole) {
public User(@NonNull String userID) {
this.userID = userID;
this.userName = userName;
this.userProfilePictureUrl = userProfilePictureUrl;
this.userInterestedEvents = userInterestedEvents;
this.userGoingEvents = userGoingEvents;
this.userEmail = userEmail;
this.userRollNumber = userRollNumber;
this.userContactNumber = userContactNumber;
this.showContactNumber = showContactNumber;
this.userAbout = userAbout;
this.userFollowedBodies = userFollowedBodies;
this.userFollowedBodiesID = userFollowedBodiesID;
this.userRoles = userRoles;
this.userInstituteRoles = userInstituteRoles;
this.userFormerRoles = userFormerRoles;
this.userWebsiteURL = userWebsiteURL;
this.userLDAPId = userLDAPId;
this.hostel = hostel;
this.currentRole = currentRole;
}
public static User fromString(String json) {
......
......@@ -136,7 +136,7 @@ public class AddEventFragment extends BaseFragment {
return view;
}
void openEvent(Event event) {
private void openEvent(Event event) {
String eventJson = new Gson().toJson(event);
Bundle bundle = getArguments();
if (bundle == null)
......@@ -151,7 +151,7 @@ public class AddEventFragment extends BaseFragment {
transaction.addToBackStack(eventFragment.getTag()).commit();
}
void openBody(Body body) {
private void openBody(Body body) {
BodyFragment bodyFragment = BodyFragment.newInstance(body);
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
......
......@@ -27,7 +27,7 @@ import app.insti.api.model.Body;
* create an instance of this fragment.
*/
public class BodyRecyclerViewFragment extends Fragment implements TransitionTargetFragment, TransitionTargetChild {
private static final String TAG = "BodyRecyclerViewFragment";
public static final String TAG = "BodyRecyclerViewFragment";
public Fragment parentFragment = null;
private RecyclerView recyclerView;
......
......@@ -230,6 +230,8 @@ public class CalendarFragment extends BaseFragment {
@Override
public void onResponse(Call<NewsFeedResponse> call, Response<NewsFeedResponse> response) {
if (response.isSuccessful()) {
if (getActivity() == null || getView() == null) return;
// Concatenate the response
NewsFeedResponse newsFeedResponse = response.body();
List<Event> eventList = newsFeedResponse.getEvents();
......
......@@ -51,7 +51,7 @@ public class ComplaintsFragment extends BaseFragment {
FileComplaintFragment fileComplaintFragment = new FileComplaintFragment();
fileComplaintFragment.setArguments(getArguments());
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.framelayout_for_fragment, fileComplaintFragment, fileComplaintFragment.getTag());
fragmentTransaction.replace(R.id.framelayout_for_fragment, fileComplaintFragment, Utils.getTag(fileComplaintFragment));
fragmentTransaction.addToBackStack("Complaint Fragment").commit();
}
});
......
......@@ -65,14 +65,10 @@ import ru.noties.markwon.Markwon;
* A simple {@link Fragment} subclass.
*/
public class EventFragment extends BackHandledFragment implements TransitionTargetFragment {
Event event;
Button goingButton;
Button interestedButton;
ImageButton navigateButton;
ImageButton webEventButton;
ImageButton shareEventButton;
RecyclerView bodyRecyclerView;
String TAG = "EventFragment";
private Event event;
private Button goingButton;
private Button interestedButton;
public String TAG = "EventFragment";
private int appBarOffset = 0;
private boolean creatingView = false;
......@@ -198,14 +194,14 @@ public class EventFragment extends BackHandledFragment implements TransitionTarg
private void inflateViews(final Event event) {
eventPicture = (ImageView) getActivity().findViewById(R.id.event_picture_2);
TextView eventTitle = (TextView) getActivity().findViewById(R.id.event_page_title);
TextView eventDate = (TextView) getActivity().findViewById(R.id.event_page_date);
TextView eventDescription = (TextView) getActivity().findViewById(R.id.event_page_description);
final TextView eventTitle = (TextView) getActivity().findViewById(R.id.event_page_title);
final TextView eventDate = (TextView) getActivity().findViewById(R.id.event_page_date);
final TextView eventDescription = (TextView) getActivity().findViewById(R.id.event_page_description);
goingButton = getActivity().findViewById(R.id.going_button);
interestedButton = getActivity().findViewById(R.id.interested_button);
navigateButton = getActivity().findViewById(R.id.navigate_button);
webEventButton = getActivity().findViewById(R.id.web_event_button);
shareEventButton = getActivity().findViewById(R.id.share_event_button);
final ImageButton navigateButton = getActivity().findViewById(R.id.navigate_button);
final ImageButton webEventButton = getActivity().findViewById(R.id.web_event_button);
final ImageButton shareEventButton = getActivity().findViewById(R.id.share_event_button);
if (event.isEventBigImage() || !creatingView) {
Picasso.get().load(event.getEventImageURL()).into(eventPicture);
......@@ -221,7 +217,7 @@ public class EventFragment extends BackHandledFragment implements TransitionTarg
SimpleDateFormat simpleDateFormatTime = new SimpleDateFormat("HH:mm");
final List<Body> bodyList = event.getEventBodies();
bodyRecyclerView = (RecyclerView) getActivity().findViewById(R.id.body_card_recycler_view);
final RecyclerView bodyRecyclerView = getActivity().findViewById(R.id.body_card_recycler_view);
BodyAdapter bodyAdapter = new BodyAdapter(bodyList, this);
bodyRecyclerView.setAdapter(bodyAdapter);
bodyRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
......
......@@ -41,7 +41,7 @@ import retrofit2.Response;
public class ExploreFragment extends Fragment {
private RecyclerView recyclerView;
LinearLayoutManager mLayoutManager;
private LinearLayoutManager mLayoutManager;
private static List<Body> allBodies = new ArrayList<>();
private static List<Body> bodies = new ArrayList<>();
......
......@@ -35,7 +35,7 @@ public class FeedFragment extends BaseFragment {
private RecyclerView feedRecyclerView;
private SwipeRefreshLayout feedSwipeRefreshLayout;
private FloatingActionButton fab;
LinearLayoutManager mLayoutManager;
private LinearLayoutManager mLayoutManager;
private int index = -1, top = -1;
private FeedAdapter feedAdapter = null;
......
......@@ -69,10 +69,10 @@ import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import app.insti.Constants;
import app.insti.ComplaintDescriptionAutoCompleteTextView;
import app.insti.R;
import app.insti.ComplaintTag;
import app.insti.Constants;
import app.insti.R;
import app.insti.Utils;
import app.insti.activity.MainActivity;
import app.insti.adapter.ImageViewPagerAdapter;
......@@ -95,7 +95,7 @@ import static app.insti.Constants.RESULT_LOAD_IMAGE;
public class FileComplaintFragment extends Fragment {
private static final String TAG = FileComplaintFragment.class.getSimpleName();
public static final String TAG = FileComplaintFragment.class.getSimpleName();
private static FileComplaintFragment mainactivity;
private Button buttonSubmit;
private ComplaintDescriptionAutoCompleteTextView descriptionAutoCompleteTextview;
......
......@@ -6,19 +6,16 @@ import android.animation.ValueAnimator;
import android.content.Context;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
......@@ -27,8 +24,6 @@ import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.SpannableStringBuilder;
......@@ -41,7 +36,6 @@ import android.text.util.Linkify;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
......@@ -61,11 +55,15 @@ import android.widget.Toast;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.SettingsClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.mrane.campusmap.ExpandableListAdapter;
......@@ -103,6 +101,9 @@ import static app.insti.Constants.MY_PERMISSIONS_REQUEST_LOCATION;
public class MapFragment extends Fragment implements TextWatcher,
TextView.OnEditorActionListener, AdapterView.OnItemClickListener, View.OnFocusChangeListener,
View.OnTouchListener, ExpandableListView.OnChildClickListener {
public static final String TAG = MapFragment.class.getSimpleName();
public static final PointF MAP_CENTER = new PointF(2971f, 1744f);
public static final long DURATION_INIT_MAP_ANIM = 500;
public static final String FONT_SEMIBOLD = "rigascreen_bold.ttf";
......@@ -110,8 +111,6 @@ public class MapFragment extends Fragment implements TextWatcher,
public static final int SOUND_ID_RESULT = 0;
public static final int SOUND_ID_ADD = 1;
public static final int SOUND_ID_REMOVE = 2;
private static final String INSTANCE_CARD_STATE = "instanceCardState";
private static final String INSTANCE_VISIBILITY_INDEX = "instanceVisibilityIndex";
private static MapFragment mainactivity;
private final String firstStackTag = "FIRST_TAG";
private final int MSG_ANIMATE = 1;
......@@ -124,7 +123,7 @@ public class MapFragment extends Fragment implements TextWatcher,
public TextView placeNameTextView;
public TextView placeSubHeadTextView;
public EditText editText;
public HashMap<String, com.mrane.data.Marker> data;
public HashMap<String, Marker> data;
public FragmentTransaction transaction;
public CampusMapView campusMapView;
public ImageButton addMarkerIcon;
......@@ -137,18 +136,22 @@ public class MapFragment extends Fragment implements TextWatcher,
private ListFragment listFragment;
private Fragment fragment;
private RelativeLayout fragmentContainer;
private View actionBarView;
private List<com.mrane.data.Marker> markerlist;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private List<Marker> markerlist;
private SlidingUpPanelLayout slidingLayout;
private CardSlideListener cardSlideListener;
private boolean noFragments = true;
private boolean editTextFocused = false;
private Toast toast;
private String message = "Sorry, no such place in our data.";
private boolean creatingView = false;
private List<Venue> venues;
private boolean GPSIsSetup = false;
private boolean followingUser = false;
private FusedLocationProviderClient fusedLocationProviderClient;
private MyLocationCallback myLocationCallback;
private LocationRequest mLocationRequest;
private Marker user = new Marker("You", "", 0, 0, -10, "");
private Handler mHandler = new Handler() {
@Override
......@@ -210,6 +213,7 @@ public class MapFragment extends Fragment implements TextWatcher,
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
creatingView = true;
return inflater.inflate(R.layout.fragment_map, container, false);
}
......@@ -226,9 +230,36 @@ public class MapFragment extends Fragment implements TextWatcher,
/* Initialize */
editText = (EditText) getView().findViewById(R.id.search);
setFonts();
getAPILocations();
if (markerlist == null) {
setFonts();
getAPILocations();
} else if (creatingView) {
setFonts();
if (venues != null) setupWithData(venues);
else getAPILocations();
}
creatingView = false;
}
@Override
public void onPause() {
if (fusedLocationProviderClient != null && myLocationCallback != null) {
fusedLocationProviderClient.removeLocationUpdates(myLocationCallback);
}
super.onPause();
}
@Override
public void onResume() {
if (fusedLocationProviderClient != null && myLocationCallback != null) {
try {
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, myLocationCallback, Looper.myLooper());
} catch (SecurityException ignored) {}
}
super.onResume();
}
private void getAPILocations() {
......@@ -237,27 +268,10 @@ public class MapFragment extends Fragment implements TextWatcher,
@Override
public void onResponse(Call<List<Venue>> call, Response<List<Venue>> response) {
if (response.isSuccessful()) {
// Setup fade animation for background
int colorFrom = Utils.getAttrColor(getContext(), R.attr.themeColor);
int colorTo = getResources().getColor(R.color.colorGray);
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.setDuration(250); // milliseconds
colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
getView().findViewById(R.id.main_container).setBackgroundColor(
(int) animator.getAnimatedValue()
);
}
});
colorAnimation.start();
// Show the location fab
((FloatingActionButton) getView().findViewById(R.id.locate_fab)).show();
if (getActivity() == null || getView() == null || getContext() == null) return;
// Show the map and data
setupWithData(response.body());
venues = response.body();
setupWithData(venues);
}
}
......@@ -269,10 +283,32 @@ public class MapFragment extends Fragment implements TextWatcher,
}
void setupWithData(List<Venue> venues) {
if (getView() == null || getActivity() == null) return;
if (getActivity() == null || getView() == null || getContext() == null) return;
// Setup fade animation for background
int colorFrom = Utils.getAttrColor(getContext(), R.attr.themeColor);
int colorTo = getResources().getColor(R.color.colorGray);
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.setDuration(250); // milliseconds
colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
if (getActivity() == null || getView() == null) return;
getView().findViewById(R.id.main_container).setBackgroundColor(
(int) animator.getAnimatedValue()
);
}
});
colorAnimation.start();
// Show the location fab
if (getView() == null) return;
((FloatingActionButton) getView().findViewById(R.id.locate_fab)).show();
// Start the setup
Locations mLocations = new Locations(venues);
data = mLocations.data;
markerlist = new ArrayList<com.mrane.data.Marker>(data.values());
markerlist = new ArrayList<>(data.values());
if (getArguments() != null) {
setupMap(getArguments().getString(Constants.MAP_INITIAL_MARKER));
}
......@@ -282,15 +318,22 @@ public class MapFragment extends Fragment implements TextWatcher,
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
locate();
locate(true);
}
});
// Setup GPS if already has permission
String permission = Manifest.permission.ACCESS_FINE_LOCATION;
int res = getContext().checkCallingOrSelfPermission(permission);
if (res == PackageManager.PERMISSION_GRANTED) {
locate(false);
}
}
private void locate() {
private void locate(boolean showWarning) {
followingUser = true;
if (!GPSIsSetup) {
displayLocationSettingsRequest(getContext());
displayLocationSettingsRequest(showWarning);
} else if (user != null) {
if (!campusMapView.isAddedMarker(user)) {
campusMapView.addMarker(user);
......@@ -363,22 +406,6 @@ public class MapFragment extends Fragment implements TextWatcher,
getActivity().findViewById(R.id.loadingPanel).setVisibility(View.GONE);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void initShowDefault() {
String[] keys = {"Convocation Hall", "Hostel 13 House of Titans",
"Hostel 15", "Main Gate no. 2",
......@@ -426,12 +453,8 @@ public class MapFragment extends Fragment implements TextWatcher,
Runnable runnable = new Runnable() {
@Override
public void run() {
int totalHeight = slidingLayout.getHeight();
int expandedCardHeight = getResources().getDimensionPixelSize(
R.dimen.expanded_card_height);
float anchorPoint = 0.5f;
slidingLayout.setAnchorPoint(anchorPoint);
Log.d("testing", "Anchor point = " + anchorPoint);
}
};
......@@ -543,7 +566,7 @@ public class MapFragment extends Fragment implements TextWatcher,
String key = editText.getText().toString();
// get Marker object if exists
com.mrane.data.Marker marker = data.get(key);
Marker marker = data.get(key);
// display and zoom to marker if exists
if (marker != null) {
......@@ -558,17 +581,12 @@ public class MapFragment extends Fragment implements TextWatcher,
}
private void showResultOnMap(String key) {
com.mrane.data.Marker marker = data.get(key);
Marker marker = data.get(key);
showCard(marker);
campusMapView.setAndShowResultMarker(marker);
}
public void showCard() {
com.mrane.data.Marker marker = campusMapView.getResultMarker();
showCard(marker);
}
public void showCard(com.mrane.data.Marker marker) {
public void showCard(Marker marker) {
String name = marker.getName();
if (!marker.getShortName().equals("0"))
name = marker.getShortName();
......@@ -584,7 +602,7 @@ public class MapFragment extends Fragment implements TextWatcher,
cardSlideListener.showCard();
}
private void setImage(LinearLayout parent, com.mrane.data.Marker marker) {
private void setImage(LinearLayout parent, Marker marker) {
View v = getLayoutInflater().inflate(R.layout.map_card_image, parent);
ImageView iv = (ImageView) v.findViewById(R.id.place_image);
int imageId = getResources().getIdentifier(marker.getImageUri(),
......@@ -592,7 +610,7 @@ public class MapFragment extends Fragment implements TextWatcher,
iv.setImageResource(imageId);
}
private void addDescriptionView(com.mrane.data.Marker marker) {
private void addDescriptionView(Marker marker) {
LinearLayout parent = (LinearLayout) getActivity().findViewById(R.id.other_details);
parent.removeAllViews();
if (!marker.getImageUri().isEmpty()) {
......@@ -678,7 +696,7 @@ public class MapFragment extends Fragment implements TextWatcher,
}
private SpannableStringBuilder getDescriptionText(com.mrane.data.Marker marker) {
private SpannableStringBuilder getDescriptionText(Marker marker) {
String text = marker.getDescription();
SpannableStringBuilder desc = new SpannableStringBuilder(text);
String[] toBoldParts = {"Email", "Phone No.", "Fax No."};
......@@ -697,18 +715,18 @@ public class MapFragment extends Fragment implements TextWatcher,
SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
}
private void setSubHeading(com.mrane.data.Marker marker) {
private void setSubHeading(Marker marker) {
SpannableStringBuilder result = new SpannableStringBuilder("");
result.append(marker.getName());
if (marker instanceof Room) {
Room room = (Room) marker;
String tag = room.tag;
if (!tag.equals("Inside")) {
if (!"Inside".equals(tag)) {
tag += ",";
} else {
tag = "in";
}
com.mrane.data.Marker parent = data.get(room.parentKey);
Marker parent = data.get(room.parentKey);
final String parentKey = parent.getName();
String parentName = parent.getName();
if (!parent.getShortName().equals("0"))
......@@ -789,17 +807,17 @@ public class MapFragment extends Fragment implements TextWatcher,
placeSubHeadTextView.setText(result);
}
private Drawable getLockIcon(com.mrane.data.Marker marker) {
private Drawable getLockIcon(Marker marker) {
int color = marker.getColor();
int drawableId = R.drawable.lock_all_off;
if (campusMapView.isAddedMarker(marker)) {
if (color == com.mrane.data.Marker.COLOR_BLUE)
if (color == Marker.COLOR_BLUE)
drawableId = R.drawable.lock_blue_on;
else if (color == com.mrane.data.Marker.COLOR_YELLOW)
else if (color == Marker.COLOR_YELLOW)
drawableId = R.drawable.lock_on_yellow;
else if (color == com.mrane.data.Marker.COLOR_GREEN)
else if (color == Marker.COLOR_GREEN)
drawableId = R.drawable.lock_green_on;
else if (color == com.mrane.data.Marker.COLOR_GRAY)
else if (color == Marker.COLOR_GRAY)
drawableId = R.drawable.lock_gray_on;
}
Drawable lock = getResources().getDrawable(drawableId);
......@@ -811,11 +829,11 @@ public class MapFragment extends Fragment implements TextWatcher,
}
private void reCenterMarker() {
com.mrane.data.Marker marker = campusMapView.getResultMarker();
Marker marker = campusMapView.getResultMarker();
reCenterMarker(marker);
}
private void reCenterMarker(com.mrane.data.Marker marker) {
private void reCenterMarker(Marker marker) {
PointF p = marker.getPoint();
float shift = getResources().getDimension(R.dimen.expanded_card_height) / 2.0f;
PointF center = new PointF(p.x, p.y + shift);
......@@ -870,7 +888,7 @@ public class MapFragment extends Fragment implements TextWatcher,
}
private void setOldText() {
com.mrane.data.Marker oldMarker = campusMapView.getResultMarker();
Marker oldMarker = campusMapView.getResultMarker();
if (oldMarker == null) {
if (editText.length() > 0) {
editText.getText().clear();
......@@ -899,11 +917,7 @@ public class MapFragment extends Fragment implements TextWatcher,
private boolean handleRemoveIcon() {
String text = editText.getText().toString();
if (text.isEmpty() || text.equals(null)) {
return false;
} else {
return true;
}
return !text.isEmpty();
}
@Override
......@@ -955,7 +969,7 @@ public class MapFragment extends Fragment implements TextWatcher,
setAddMarkerIcon(campusMapView.getResultMarker());
}
private void setAddMarkerIcon(com.mrane.data.Marker m) {
private void setAddMarkerIcon(Marker m) {
addMarkerIcon.setImageDrawable(getLockIcon(m));
}
......@@ -978,7 +992,7 @@ public class MapFragment extends Fragment implements TextWatcher,
return slidingLayout;
}
public void setupGPS() {
public void setupGPS(boolean showWarning) {
if (getView() == null || getActivity() == null) return;
// Permissions stuff
if (ContextCompat.checkSelfPermission(getActivity(),
......@@ -988,14 +1002,32 @@ public class MapFragment extends Fragment implements TextWatcher,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
LocationManager locationManager = (LocationManager)
getActivity().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 50, 1, locationListener);
// Create the location request to start receiving updates
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(500);
mLocationRequest.setFastestInterval(200);
// Create LocationSettingsRequest object using location request
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// Check whether location settings are satisfied
SettingsClient settingsClient = LocationServices.getSettingsClient(getActivity());
settingsClient.checkLocationSettings(locationSettingsRequest);
// Setup the callback
myLocationCallback = new MyLocationCallback();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, myLocationCallback, Looper.myLooper());
GPSIsSetup = true;
Toast.makeText(getContext(), "WARNING: Location is in Beta. Use with Caution.", Toast.LENGTH_LONG).show();
if (showWarning) {
Toast.makeText(getContext(), "WARNING: Location is in Beta. Use with Caution.", Toast.LENGTH_LONG).show();
}
} catch (SecurityException ignored) {
Toast.makeText(getContext(), "No permission!", Toast.LENGTH_LONG).show();
}
......@@ -1006,7 +1038,7 @@ public class MapFragment extends Fragment implements TextWatcher,
this.followingUser = followingUser;
}
private void displayLocationSettingsRequest(Context context) {
private void displayLocationSettingsRequest(final boolean showWarning) {
if (getView() == null || getActivity() == null) return;
LocationRequest mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
......@@ -1026,7 +1058,7 @@ public class MapFragment extends Fragment implements TextWatcher,
result.getLocationSettingsStates().isGpsUsable() &&
result.getLocationSettingsStates().isLocationPresent() &&
result.getLocationSettingsStates().isLocationUsable()) {
setupGPS();
setupGPS(showWarning);
}
} catch (ApiException ex) {
switch (ex.getStatusCode()) {
......@@ -1036,7 +1068,7 @@ public class MapFragment extends Fragment implements TextWatcher,
(ResolvableApiException) ex;
resolvableApiException
.startResolutionForResult(getActivity(), 87);
setupGPS();
setupGPS(showWarning);
} catch (IntentSender.SendIntentException e) {
}
break;
......@@ -1087,17 +1119,16 @@ public class MapFragment extends Fragment implements TextWatcher,
}
/*---------- Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
private class MyLocationCallback extends LocationCallback {
@Override
public void onLocationChanged(Location loc) {
public void onLocationResult(LocationResult locationResult) {
if (getView() == null || getActivity() == null) return;
// Set the origin
double Xn = Constants.MAP_Xn, Yn = Constants.MAP_Yn, Zn = Constants.MAP_Zn, Zyn = Constants.MAP_Zyn;
double x = (loc.getLatitude() - Xn) * 1000;
double y = (loc.getLongitude() - Yn) * 1000;
double x = (locationResult.getLastLocation().getLatitude() - Xn) * 1000;
double y = (locationResult.getLastLocation().getLongitude() - Yn) * 1000;
// Pre-trained weights
double[] A = Constants.MAP_WEIGHTS_X;
......@@ -1111,25 +1142,15 @@ public class MapFragment extends Fragment implements TextWatcher,
campusMapView.addMarker(user);
}
user.setPoint(new PointF(px, py));
user.setName("You - " + (int) loc.getAccuracy() + "m");
user.setName("You - " + (int) locationResult.getLastLocation().getAccuracy() + "m");
if (followingUser) {
SubsamplingScaleImageView.AnimationBuilder anim = campusMapView.animateCenter(user.getPoint());
if (anim != null) anim.start();
}
campusMapView.invalidate();
}
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
super.onLocationResult(locationResult);
}
}
}
......
......@@ -27,9 +27,6 @@ public class RoleRecyclerViewFragment extends Fragment implements TransitionTarg
private static final String TAG = "RoleRecyclerViewFragment";
public Fragment parentFragment = null;
private RecyclerView recyclerView;
private RoleAdapter roleAdapter;
private List<Role> roleList;
public RoleRecyclerViewFragment() {
......@@ -70,8 +67,8 @@ public class RoleRecyclerViewFragment extends Fragment implements TransitionTarg
public void onStart() {
super.onStart();
recyclerView = (RecyclerView) getActivity().findViewById(R.id.role_recycler_view);
roleAdapter = new RoleAdapter(roleList, this);
RecyclerView recyclerView = (RecyclerView) getActivity().findViewById(R.id.role_recycler_view);
RoleAdapter roleAdapter = new RoleAdapter(roleList, this);
roleAdapter.uid = "RRVFrag";
recyclerView.setAdapter(roleAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
......
......@@ -24,21 +24,15 @@ import retrofit2.Callback;
import retrofit2.Response;
public class SettingsFragment extends PreferenceFragmentCompat {
private SwitchPreferenceCompat showContactPref;
private SwitchPreferenceCompat darkThemePref;
private Preference profilePref;
private Preference feedbackPref;
private Preference aboutPref;
private Preference logoutPref;
private SharedPreferences sharedPref;
private SharedPreferences.Editor editor;
private SwitchPreferenceCompat showContactPref;
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
// Get preferences and editor
sharedPref = getActivity().getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences sharedPref = getActivity().getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
editor = sharedPref.edit();
// Show contact number
......@@ -53,7 +47,7 @@ public class SettingsFragment extends PreferenceFragmentCompat {
showContactPref.setEnabled(false);
// Dark Theme
darkThemePref = (SwitchPreferenceCompat) findPreference("dark_theme");
SwitchPreferenceCompat darkThemePref = (SwitchPreferenceCompat) findPreference("dark_theme");
darkThemePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
......@@ -64,7 +58,7 @@ public class SettingsFragment extends PreferenceFragmentCompat {
darkThemePref.setChecked(sharedPref.getBoolean(Constants.DARK_THEME, false));
// Update Profile
profilePref = findPreference("profile");
Preference profilePref = findPreference("profile");
profilePref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
......@@ -74,7 +68,7 @@ public class SettingsFragment extends PreferenceFragmentCompat {
});
// Feedback
feedbackPref = findPreference("feedback");
Preference feedbackPref = findPreference("feedback");
feedbackPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
......@@ -84,7 +78,7 @@ public class SettingsFragment extends PreferenceFragmentCompat {
});
// About
aboutPref = findPreference("about");
Preference aboutPref = findPreference("about");
aboutPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
......@@ -94,7 +88,7 @@ public class SettingsFragment extends PreferenceFragmentCompat {
});
// Logout
logoutPref = findPreference("logout");
Preference logoutPref = findPreference("logout");
logoutPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
......
......@@ -116,6 +116,7 @@ public class UserFragment extends BackHandledFragment implements TransitionTarge
@Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
if (getActivity() == null || getView() == null) return;
user = response.body();
populateViews();
getActivity().findViewById(R.id.loadingPanel).setVisibility(View.GONE);
......@@ -145,6 +146,8 @@ public class UserFragment extends BackHandledFragment implements TransitionTarge
}
private void populateViews() {
if (getActivity() == null || getView() == null) return;
userProfilePictureImageView = getActivity().findViewById(R.id.user_profile_picture_profile);
TextView userNameTextView = getActivity().findViewById(R.id.user_name_profile);
TextView userRollNumberTextView = getActivity().findViewById(R.id.user_rollno_profile);
......
......@@ -17,8 +17,6 @@ import app.insti.fragment.MapFragment;
public class ListFragment extends Fragment {
MapFragment mainActivity;
FuzzySearchAdapter adapter;
HashMap<String, Marker> data;
View rootView;
ListView list;
......@@ -29,7 +27,7 @@ public class ListFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mainActivity = MapFragment.getMainActivity();
adapter = mainActivity.getAdapter();
final FuzzySearchAdapter adapter = mainActivity.getAdapter();
rootView = inflater.inflate(R.layout.map_list_fragment, container, false);
list = (ListView) rootView.findViewById(R.id.suggestion_list);
list.setAdapter(adapter);
......
......@@ -412,20 +412,17 @@ public class CampusMapView extends SubsamplingScaleImageView {
for (Marker marker : markerList) {
if (isInView(marker.getPoint())) {
if (isShowPinScale(marker)
&& !(isResultMarker(marker) || addedMarkerList
.contains(marker))) {
if (shouldShowUp(marker))
drawPionterAndText(canvas, marker);
if (isShowPinScale(marker) &&
!(isResultMarker(marker) || addedMarkerList.contains(marker)) &&
shouldShowUp(marker)) {
drawPionterAndText(canvas, marker);
}
}
}
for (Marker marker : addedMarkerList) {
if (isInView(marker.getPoint())) {
if (!isResultMarker(marker)) {
drawMarkerBitmap(canvas, marker);
drawMarkerText(canvas, marker);
}
if (isInView(marker.getPoint()) && !isResultMarker(marker)) {
drawMarkerBitmap(canvas, marker);
drawMarkerText(canvas, marker);
}
}
Marker marker = getResultMarker();
......@@ -689,8 +686,6 @@ public class CampusMapView extends SubsamplingScaleImageView {
if (motionEvent.getX() < 20 * density) {
getParent().requestDisallowInterceptTouchEvent(false);
return true;
} else {
// CampusMapView.this.setPanEnabled(true);
}
} else if (action == MotionEvent.ACTION_UP) {
CampusMapView.this.setPanEnabled(true);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment