Commit f4bc2b16 authored by MayuBhattu's avatar MayuBhattu

Merge remote-tracking branch 'upstream/master'

# Conflicts:
#	app/src/main/java/app/insti/fragment/BodyFragment.java
parents 320639a6 57049bc9
...@@ -8,8 +8,8 @@ android { ...@@ -8,8 +8,8 @@ android {
manifestPlaceholders 'appAuthRedirectScheme': 'https' manifestPlaceholders 'appAuthRedirectScheme': 'https'
minSdkVersion 21 minSdkVersion 21
targetSdkVersion 27 targetSdkVersion 27
versionCode 16 versionCode 17
versionName "1.0.11" versionName "1.0.12"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
resValue "string", "google_maps_key", (project.findProperty("GOOGLE_MAPS_API_KEY") ?: "") resValue "string", "google_maps_key", (project.findProperty("GOOGLE_MAPS_API_KEY") ?: "")
vectorDrawables.useSupportLibrary = true vectorDrawables.useSupportLibrary = true
...@@ -23,13 +23,11 @@ android { ...@@ -23,13 +23,11 @@ android {
} }
ext { ext {
supportLibVersion = '27.1.1' supportLibVersion = '27.1.0'
playServicesVersion = '15.0.1' playServicesVersion = '15.0.1'
butterKnifeVersion = '8.8.1'
retrofitVersion = '2.3.0' retrofitVersion = '2.3.0'
okhttpVersion = '3.11.0' okhttpVersion = '3.11.0'
picassoVersion = '2.71828' picassoVersion = '2.71828'
archRoomVersion = '1.1.1'
circleImageViewVersion = '2.2.0' circleImageViewVersion = '2.2.0'
markwonVersion = '1.0.6' markwonVersion = '1.0.6'
} }
...@@ -37,25 +35,14 @@ ext { ...@@ -37,25 +35,14 @@ ext {
dependencies { dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar']) implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.firebase:firebase-messaging:17.1.0' implementation 'com.google.firebase:firebase-messaging:17.1.0'
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testImplementation "junit:junit:4.12"
implementation "com.android.support:design:${supportLibVersion}" implementation "com.android.support:design:${supportLibVersion}"
implementation "com.android.support:support-v4:${supportLibVersion}" implementation "com.android.support:support-v4:${supportLibVersion}"
implementation "com.jakewharton:butterknife:${butterKnifeVersion}"
implementation "com.google.android.gms:play-services-gcm:${playServicesVersion}"
implementation "com.google.android.gms:play-services-maps:${playServicesVersion}"
implementation "com.google.android.gms:play-services-location:${playServicesVersion}" implementation "com.google.android.gms:play-services-location:${playServicesVersion}"
annotationProcessor "com.jakewharton:butterknife-compiler:${butterKnifeVersion}"
implementation "com.squareup.retrofit2:retrofit:${retrofitVersion}" implementation "com.squareup.retrofit2:retrofit:${retrofitVersion}"
implementation "com.squareup.retrofit2:converter-gson:${retrofitVersion}" implementation "com.squareup.retrofit2:converter-gson:${retrofitVersion}"
implementation "com.squareup.okhttp3:okhttp:${okhttpVersion}" implementation "com.squareup.okhttp3:okhttp:${okhttpVersion}"
implementation "com.squareup.okhttp3:logging-interceptor:${okhttpVersion}" implementation "com.squareup.okhttp3:logging-interceptor:${okhttpVersion}"
implementation "com.squareup.picasso:picasso:${picassoVersion}" implementation "com.squareup.picasso:picasso:${picassoVersion}"
implementation "com.android.support:customtabs:${supportLibVersion}"
implementation "android.arch.persistence.room:runtime:${archRoomVersion}"
annotationProcessor "android.arch.persistence.room:compiler:${archRoomVersion}"
implementation "com.android.support:cardview-v7:${supportLibVersion}" implementation "com.android.support:cardview-v7:${supportLibVersion}"
implementation "de.hdodenhof:circleimageview:${circleImageViewVersion}" implementation "de.hdodenhof:circleimageview:${circleImageViewVersion}"
implementation "ru.noties:markwon:${markwonVersion}" implementation "ru.noties:markwon:${markwonVersion}"
......
...@@ -3,10 +3,12 @@ ...@@ -3,10 +3,12 @@
package="app.insti"> package="app.insti">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE" />
<application <application
android:allowBackup="true" android:allowBackup="true"
...@@ -66,39 +68,6 @@ ...@@ -66,39 +68,6 @@
android:pathPattern="/event/.*" android:pathPattern="/event/.*"
android:scheme="https" /> android:scheme="https" />
</intent-filter> </intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="insti.app"
android:pathPattern="/org/.*"
android:scheme="http" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="insti.app"
android:pathPattern="/user/.*"
android:scheme="http" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="insti.app"
android:pathPattern="/event/.*"
android:scheme="http" />
</intent-filter>
</activity> </activity>
<activity <activity
android:name=".activity.LoginActivity" android:name=".activity.LoginActivity"
...@@ -116,21 +85,6 @@ ...@@ -116,21 +85,6 @@
</activity> </activity>
<service
android:name=".notifications.NotificationIntentService"
android:enabled="true"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE" />
<receiver android:name=".notifications.NotificationEventReceiver" />
<receiver android:name=".notifications.NotificationServiceStarterReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
<action android:name="android.intent.action.TIME_SET" />
</intent-filter>
</receiver>
<service android:name=".InstiAppFirebaseMessagingService"> <service android:name=".InstiAppFirebaseMessagingService">
<intent-filter> <intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" /> <action android:name="com.google.firebase.MESSAGING_EVENT" />
......
...@@ -28,8 +28,34 @@ public class Constants { ...@@ -28,8 +28,34 @@ public class Constants {
public static final String LOGIN_MESSAGE = "Please login to continue!"; public static final String LOGIN_MESSAGE = "Please login to continue!";
public static final String MAIN_INTENT_EXTRAS = "MAIN_EXTRA";
public static final String FCM_BUNDLE_TYPE = "type";
public static final String FCM_BUNDLE_ID = "id";
public static final String FCM_BUNDLE_EXTRA = "extra";
public static final String FCM_BUNDLE_NOTIFICATION_ID = "notification_id";
public static final String FCM_BUNDLE_ACTION = "action";
public static final String FCM_BUNDLE_RICH = "rich";
public static final String FCM_BUNDLE_TITLE = "title";
public static final String FCM_BUNDLE_VERB = "verb";
public static final String FCM_BUNDLE_IMAGE = "image_url";
public static final String FCM_BUNDLE_LARGE_ICON = "large_icon";
public static final String FCM_BUNDLE_LARGE_CONTENT = "large_content";
public static final String FCM_BUNDLE_ACTION_STARTING = "starting";
public static final String DATA_TYPE_EVENT = "event";
public static final String DATA_TYPE_BODY = "body";
public static final String DATA_TYPE_USER = "userprofile";
public static final String DATA_TYPE_NEWS = "newsentry";
public static final String DATA_TYPE_PT = "blogentry";
/* Map */ /* Map */
public static final double MAP_Xn = 19.134417, MAP_Yn = 72.901229, MAP_Zn = 1757, MAP_Zyn = 501; public static final double MAP_Xn = 19.134417, MAP_Yn = 72.901229, MAP_Zn = 1757, MAP_Zyn = 501;
public static final double[] MAP_WEIGHTS_X = {-11.392001766454612, -36.31634553309953, 73.91269388324432, -24.14021153064087, 3.4508817531539115, -0.1462262375477863, 5.532505074667804, -1.542391995870977, 36.14211738142935}; public static final double[] MAP_WEIGHTS_X = {-11.392001766454612, -36.31634553309953, 73.91269388324432, -24.14021153064087, 3.4508817531539115, -0.1462262375477863, 5.532505074667804, -1.542391995870977, 36.14211738142935};
public static final double[] MAP_WEIGHTS_Y = {0.09738953520399705, -4.519868444089616, 62.38493718381985, 16.664561869057696, -2.168377988768651, 0.0919143297622087, 0.32304266159540823, 0.21688067854428716, -12.81393255320748}; public static final double[] MAP_WEIGHTS_Y = {0.09738953520399705, -4.519868444089616, 62.38493718381985, 16.664561869057696, -2.168377988768651, 0.0919143297622087, 0.32304266159540823, 0.21688067854428716, -12.81393255320748};
public static final String resizeImageUrl(String url, Integer dim) {
if (url == null) { return url; }
return url.replace("api.insti.app/static/", "img.insti.app/static/" + dim.toString() + "/");
}
} }
package app.insti; package app.insti;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage; import com.google.firebase.messaging.RemoteMessage;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.util.Map;
import app.insti.activity.MainActivity;
import app.insti.notifications.NotificationId;
public class InstiAppFirebaseMessagingService extends FirebaseMessagingService { public class InstiAppFirebaseMessagingService extends FirebaseMessagingService {
String channel;
@Override @Override
public void onNewToken(String s) { public void onNewToken(String s) {
/* For future functionality */ /* For future functionality */
super.onNewToken(s); super.onNewToken(s);
} }
/** Convert a string to string map to a bundle */
private Bundle stringMapToBundle(Map<String, String> map) {
Bundle bundle = new Bundle();
for (Map.Entry<String, String> entry : map.entrySet()) {
bundle.putString(entry.getKey(), entry.getValue());
}
return bundle;
}
/** Get a PendingIntent to open MainActivity from a notification message */
private PendingIntent getNotificationIntent(RemoteMessage remoteMessage, Integer notificationId) {
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra(Constants.MAIN_INTENT_EXTRAS, stringMapToBundle(remoteMessage.getData()));
return PendingIntent.getActivity(this, notificationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override @Override
public void onMessageReceived(RemoteMessage remoteMessage) { public void onMessageReceived(RemoteMessage remoteMessage) {
/* For future functionality */ channel = getResources().getString(R.string.default_notification_channel_id);
// Check for empty data notifications
if (remoteMessage.getData().size() > 0) {
sendRichNotification(remoteMessage);
}
super.onMessageReceived(remoteMessage); super.onMessageReceived(remoteMessage);
} }
/** Ensure key is in data */
private boolean ensureKeyExists(RemoteMessage remoteMessage, String key) {
return (remoteMessage.getData().get(key) != null);
}
/** Send a rich notification with image support */
private void sendRichNotification(RemoteMessage remoteMessage) {
if (!ensureKeyExists(remoteMessage, Constants.FCM_BUNDLE_TITLE) ||
!ensureKeyExists(remoteMessage, Constants.FCM_BUNDLE_VERB)) { return; }
final String message = remoteMessage.getData().get(Constants.FCM_BUNDLE_VERB);
/* Get unique id */
int notification_id = NotificationId.getID();
/* Default options */
NotificationCompat.Builder builder = standardNotificationBuilder()
.setContentTitle(remoteMessage.getData().get(Constants.FCM_BUNDLE_TITLE))
.setContentText(message)
.setContentIntent(getNotificationIntent(remoteMessage, notification_id));
/* Check for article */
String largeContent = remoteMessage.getData().get(Constants.FCM_BUNDLE_LARGE_CONTENT);
if (largeContent != null) {
builder.setStyle(new NotificationCompat.BigTextStyle()
.bigText(largeContent));
}
/* Get images and show */
showBitmapNotification(
this,
remoteMessage.getData().get(Constants.FCM_BUNDLE_IMAGE),
remoteMessage.getData().get(Constants.FCM_BUNDLE_LARGE_ICON),
notification_id,
builder,
message
);
}
/** Show the notification */
private static void showNotification(Context context, int id, Notification notification) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(id, notification);
}
/** Common builder */
private NotificationCompat.Builder standardNotificationBuilder() {
Uri soundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
return new NotificationCompat.Builder(this, channel)
.setSmallIcon(R.drawable.ic_lotusgray)
.setColor(getResources().getColor(R.color.colorPrimary))
.setVibrate(new long[]{0, 200})
.setSound(soundUri)
.setLights(Color.BLUE, 500, 500)
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
}
/** Gets a bitmap from a URL asynchronously and shows notification */
public static void showBitmapNotification(
final Context context, final String imageUrl, final String largeIconUrl,
final int notification_id, final NotificationCompat.Builder builder, final String content){
new AsyncTask<Void, Void, Bitmap[]>() {
@Override
protected Bitmap[] doInBackground(Void... params) {
try {
Bitmap image = null;
if (imageUrl != null) {
image = Picasso.get().load(imageUrl).get();
}
Bitmap largeIcon = null;
if (largeIconUrl != null) {
largeIcon = getCroppedBitmap(
Picasso.get().load(Constants.resizeImageUrl(largeIconUrl, 200)).get(), 200);
}
return new Bitmap[]{image, largeIcon};
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap[] bitmaps) {
// Check if we loaded big image
if (bitmaps != null && bitmaps[0] != null) {
builder.setStyle(
new NotificationCompat.BigPictureStyle()
.bigPicture(bitmaps[0])
.setSummaryText(content)
);
}
// Check if we loaded large icon
if (bitmaps != null && bitmaps[1] != null) {
builder.setLargeIcon(bitmaps[1]);
}
showNotification(context, notification_id, builder.build());
super.onPostExecute(bitmaps);
}
}.execute();
}
/** Get circular center cropped bitmap */
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp, (int)(bmp.getWidth() / factor), (int)(bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xffa19774;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
final Rect destRect = new Rect(
(sbmp.getWidth() - radius) / 2,
(sbmp.getHeight() - radius) / 2,
radius + (sbmp.getWidth() - radius) / 2,
radius + (sbmp.getHeight() - radius) / 2);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
canvas.drawCircle(radius / 2,
radius / 2, radius / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(sbmp, destRect, rect, paint);
return output;
}
} }
...@@ -7,7 +7,7 @@ import android.content.SharedPreferences.Editor; ...@@ -7,7 +7,7 @@ import android.content.SharedPreferences.Editor;
import android.util.Log; import android.util.Log;
import app.insti.activity.LoginActivity; import app.insti.activity.LoginActivity;
import app.insti.data.User; import app.insti.api.model.User;
public class SessionManager { public class SessionManager {
public SharedPreferences pref; public SharedPreferences pref;
......
package app.insti; package app.insti;
import app.insti.data.Body; import app.insti.api.model.Body;
import app.insti.data.Event; import app.insti.api.model.Event;
import app.insti.data.User; import app.insti.api.model.User;
/** /**
* Created by varun on 03-Apr-18. * Created by varun on 03-Apr-18.
......
...@@ -18,11 +18,12 @@ import com.google.android.gms.tasks.OnSuccessListener; ...@@ -18,11 +18,12 @@ import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult; import com.google.firebase.iid.InstanceIdResult;
import app.insti.Constants;
import app.insti.R; import app.insti.R;
import app.insti.SessionManager; import app.insti.SessionManager;
import app.insti.api.RetrofitInterface; import app.insti.api.RetrofitInterface;
import app.insti.api.ServiceGenerator; import app.insti.api.ServiceGenerator;
import app.insti.api.model.LoginResponse; import app.insti.api.response.LoginResponse;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
...@@ -40,6 +41,11 @@ public class LoginActivity extends AppCompatActivity { ...@@ -40,6 +41,11 @@ public class LoginActivity extends AppCompatActivity {
private boolean loggingIn = false; private boolean loggingIn = false;
private ProgressDialog progressDialog; private ProgressDialog progressDialog;
private RetrofitInterface retrofitInterface;
public RetrofitInterface getRetrofitInterface() {
return retrofitInterface;
}
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
...@@ -53,6 +59,13 @@ public class LoginActivity extends AppCompatActivity { ...@@ -53,6 +59,13 @@ public class LoginActivity extends AppCompatActivity {
private void openMainActivity() { private void openMainActivity() {
Intent i = new Intent(mContext, MainActivity.class); Intent i = new Intent(mContext, MainActivity.class);
/* Pass FCM data if available */
Intent myIntent = getIntent();
if (myIntent.getExtras() != null) {
i.putExtra(Constants.MAIN_INTENT_EXTRAS, myIntent.getExtras());
}
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i); startActivity(i);
...@@ -63,6 +76,9 @@ public class LoginActivity extends AppCompatActivity { ...@@ -63,6 +76,9 @@ public class LoginActivity extends AppCompatActivity {
protected void onStart() { protected void onStart() {
super.onStart(); super.onStart();
ServiceGenerator serviceGenerator = new ServiceGenerator(getApplicationContext());
this.retrofitInterface = serviceGenerator.getRetrofitInterface();
WebView webview = (WebView) findViewById(R.id.login_webview); WebView webview = (WebView) findViewById(R.id.login_webview);
webview.getSettings().setJavaScriptEnabled(true); webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true); webview.getSettings().setDomStorageEnabled(true);
...@@ -80,7 +96,7 @@ public class LoginActivity extends AppCompatActivity { ...@@ -80,7 +96,7 @@ public class LoginActivity extends AppCompatActivity {
private void login(final String authorizationCode, final String redirectURL) { private void login(final String authorizationCode, final String redirectURL) {
/* This can be null if play services is hung */ /* This can be null if play services is hung */
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = getRetrofitInterface();
Call<LoginResponse> call; Call<LoginResponse> call;
if (fcmId == null) { if (fcmId == null) {
call = retrofitInterface.login(authorizationCode, redirectURL); call = retrofitInterface.login(authorizationCode, redirectURL);
...@@ -118,7 +134,7 @@ public class LoginActivity extends AppCompatActivity { ...@@ -118,7 +134,7 @@ public class LoginActivity extends AppCompatActivity {
progressDialog.show(); progressDialog.show();
} }
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = getRetrofitInterface();
Call<LoginResponse> call; Call<LoginResponse> call;
/* This can be null if play services is hung */ /* This can be null if play services is hung */
......
...@@ -12,9 +12,10 @@ import com.squareup.picasso.Picasso; ...@@ -12,9 +12,10 @@ import com.squareup.picasso.Picasso;
import java.util.List; import java.util.List;
import app.insti.ItemClickListener; import app.insti.Constants;
import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.data.Body; import app.insti.api.model.Body;
public class BodyAdapter extends RecyclerView.Adapter<BodyAdapter.ViewHolder> { public class BodyAdapter extends RecyclerView.Adapter<BodyAdapter.ViewHolder> {
...@@ -51,7 +52,9 @@ public class BodyAdapter extends RecyclerView.Adapter<BodyAdapter.ViewHolder> { ...@@ -51,7 +52,9 @@ public class BodyAdapter extends RecyclerView.Adapter<BodyAdapter.ViewHolder> {
Body body = bodyList.get(position); Body body = bodyList.get(position);
holder.name.setText(body.getBodyName()); holder.name.setText(body.getBodyName());
holder.description.setText(body.getBodyShortDescription()); holder.description.setText(body.getBodyShortDescription());
Picasso.get().load(body.getBodyImageURL()).resize(0, 200).into(holder.image); Picasso.get().load(
Constants.resizeImageUrl(body.getBodyImageURL(), 200)
).into(holder.image);
} }
......
...@@ -17,10 +17,11 @@ import java.util.List; ...@@ -17,10 +17,11 @@ import java.util.List;
import java.util.Calendar; import java.util.Calendar;
import app.insti.ItemClickListener; import app.insti.Constants;
import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.data.Event; import app.insti.api.model.Event;
import app.insti.data.Venue; import app.insti.api.model.Venue;
public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.ViewHolder> { public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.ViewHolder> {
...@@ -112,17 +113,14 @@ public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.ViewHolder> { ...@@ -112,17 +113,14 @@ public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.ViewHolder> {
getSubtitle(viewHolder, currentEvent); getSubtitle(viewHolder, currentEvent);
// Fallback to image of first body if event has no image
if (currentEvent.getEventImageURL() == null) {
currentEvent.setEventImageURL(currentEvent.getEventBodies().get(0).getBodyImageURL());
}
if (currentEvent.isEventBigImage()) { if (currentEvent.isEventBigImage()) {
viewHolder.eventBigPicture.setVisibility(View.VISIBLE); viewHolder.eventBigPicture.setVisibility(View.VISIBLE);
viewHolder.eventPicture.setVisibility(View.GONE); viewHolder.eventPicture.setVisibility(View.GONE);
Picasso.get().load(currentEvent.getEventImageURL()).into(viewHolder.eventBigPicture); Picasso.get().load(currentEvent.getEventImageURL()).into(viewHolder.eventBigPicture);
} else { } else {
Picasso.get().load(currentEvent.getEventImageURL()).into(viewHolder.eventPicture); Picasso.get().load(
Constants.resizeImageUrl(currentEvent.getEventImageURL(), 200)
).into(viewHolder.eventPicture);
} }
} }
......
...@@ -11,7 +11,7 @@ import android.widget.TextView; ...@@ -11,7 +11,7 @@ import android.widget.TextView;
import java.util.List; import java.util.List;
import app.insti.R; import app.insti.R;
import app.insti.data.MessMenu; import app.insti.api.model.MessMenu;
public class MessMenuAdapter extends RecyclerView.Adapter<MessMenuAdapter.ViewHolder> { public class MessMenuAdapter extends RecyclerView.Adapter<MessMenuAdapter.ViewHolder> {
private List<MessMenu> messMenus; private List<MessMenu> messMenus;
......
...@@ -16,13 +16,15 @@ import java.util.Date; ...@@ -16,13 +16,15 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.data.NewsArticle; import app.insti.interfaces.Readable;
import app.insti.interfaces.Writable;
import app.insti.api.model.NewsArticle;
import app.insti.fragment.NewsFragment; import app.insti.fragment.NewsFragment;
import ru.noties.markwon.Markwon; import ru.noties.markwon.Markwon;
public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Readable<NewsArticle>,Writable<NewsArticle> {
private final int VIEW_ITEM = 1; private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0; private final int VIEW_PROG = 0;
...@@ -35,12 +37,14 @@ public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { ...@@ -35,12 +37,14 @@ public class NewsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
this.itemClickListener = itemClickListener; this.itemClickListener = itemClickListener;
} }
public List<NewsArticle> getNewsArticles() { @Override
public List<NewsArticle> getPosts() {
return newsArticles; return newsArticles;
} }
public void setNewsArticles(List<NewsArticle> newsArticles) { @Override
this.newsArticles = newsArticles; public void setPosts(List<NewsArticle> posts) {
this.newsArticles = posts;
} }
@NonNull @NonNull
......
...@@ -13,12 +13,13 @@ import com.squareup.picasso.Picasso; ...@@ -13,12 +13,13 @@ import com.squareup.picasso.Picasso;
import java.util.List; import java.util.List;
import app.insti.ItemClickListener; import app.insti.Constants;
import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.data.Event; import app.insti.api.model.Event;
import app.insti.data.NewsArticle; import app.insti.api.model.NewsArticle;
import app.insti.data.Notification; import app.insti.api.model.Notification;
import app.insti.data.PlacementBlogPost; import app.insti.api.model.PlacementBlogPost;
public class NotificationsAdapter extends RecyclerView.Adapter<NotificationsAdapter.Viewholder> { public class NotificationsAdapter extends RecyclerView.Adapter<NotificationsAdapter.Viewholder> {
private List<Notification> notifications; private List<Notification> notifications;
...@@ -53,11 +54,15 @@ public class NotificationsAdapter extends RecyclerView.Adapter<NotificationsAdap ...@@ -53,11 +54,15 @@ public class NotificationsAdapter extends RecyclerView.Adapter<NotificationsAdap
viewholder.notificationVerb.setText(appNotification.getNotificationVerb()); viewholder.notificationVerb.setText(appNotification.getNotificationVerb());
if (appNotification.getNotificationActorType().contains("event")) { if (appNotification.getNotificationActorType().contains("event")) {
Event event = gson.fromJson(gson.toJson(appNotification.getNotificationActor()), Event.class); Event event = gson.fromJson(gson.toJson(appNotification.getNotificationActor()), Event.class);
Picasso.get().load(event.getEventImageURL()).into(viewholder.notificationPicture); Picasso.get().load(
Constants.resizeImageUrl(event.getEventImageURL(), 200)
).into(viewholder.notificationPicture);
viewholder.notificationTitle.setText(event.getEventName()); viewholder.notificationTitle.setText(event.getEventName());
} else if (appNotification.getNotificationActorType().contains("newsentry")) { } else if (appNotification.getNotificationActorType().contains("newsentry")) {
NewsArticle article = gson.fromJson(gson.toJson(appNotification.getNotificationActor()), NewsArticle.class); NewsArticle article = gson.fromJson(gson.toJson(appNotification.getNotificationActor()), NewsArticle.class);
Picasso.get().load(article.getBody().getBodyImageURL()).into(viewholder.notificationPicture); Picasso.get().load(
Constants.resizeImageUrl(article.getBody().getBodyImageURL(), 200)
).into(viewholder.notificationPicture);
viewholder.notificationTitle.setText(article.getTitle()); viewholder.notificationTitle.setText(article.getTitle());
} else if (appNotification.getNotificationActorType().contains("blogentry")) { } else if (appNotification.getNotificationActorType().contains("blogentry")) {
PlacementBlogPost post = gson.fromJson(gson.toJson(appNotification.getNotificationActor()), PlacementBlogPost.class); PlacementBlogPost post = gson.fromJson(gson.toJson(appNotification.getNotificationActor()), PlacementBlogPost.class);
......
...@@ -15,13 +15,15 @@ import java.util.Date; ...@@ -15,13 +15,15 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.data.PlacementBlogPost; import app.insti.api.model.PlacementBlogPost;
import app.insti.fragment.PlacementBlogFragment; import app.insti.fragment.PlacementBlogFragment;
import app.insti.interfaces.Readable;
import app.insti.interfaces.Writable;
import ru.noties.markwon.Markwon; import ru.noties.markwon.Markwon;
public class PlacementBlogAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class PlacementBlogAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Readable<PlacementBlogPost>,Writable<PlacementBlogPost> {
private final int VIEW_ITEM = 1; private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0; private final int VIEW_PROG = 0;
private List<PlacementBlogPost> posts; private List<PlacementBlogPost> posts;
......
...@@ -13,10 +13,10 @@ import com.squareup.picasso.Picasso; ...@@ -13,10 +13,10 @@ import com.squareup.picasso.Picasso;
import java.util.List; import java.util.List;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.data.Body; import app.insti.api.model.Body;
import app.insti.data.Role; import app.insti.api.model.Role;
public class RoleAdapter extends RecyclerView.Adapter<RoleAdapter.ViewHolder> { public class RoleAdapter extends RecyclerView.Adapter<RoleAdapter.ViewHolder> {
......
...@@ -15,13 +15,15 @@ import java.util.Date; ...@@ -15,13 +15,15 @@ import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.data.TrainingBlogPost; import app.insti.api.model.TrainingBlogPost;
import app.insti.fragment.TrainingBlogFragment; import app.insti.fragment.TrainingBlogFragment;
import app.insti.interfaces.Readable;
import app.insti.interfaces.Writable;
import ru.noties.markwon.Markwon; import ru.noties.markwon.Markwon;
public class TrainingBlogAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { public class TrainingBlogAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements Readable<TrainingBlogPost>,Writable<TrainingBlogPost> {
private final int VIEW_ITEM = 1; private final int VIEW_ITEM = 1;
private final int VIEW_PROG = 0; private final int VIEW_PROG = 0;
......
...@@ -12,9 +12,9 @@ import com.squareup.picasso.Picasso; ...@@ -12,9 +12,9 @@ import com.squareup.picasso.Picasso;
import java.util.List; import java.util.List;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.data.User; import app.insti.api.model.User;
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> { public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
......
package app.insti.api;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class EmptyCallback<T> implements Callback<T> {
@Override
public void onResponse(Call<T> call, Response<T> response) {}
@Override
public void onFailure(Call<T> call, Throwable t) {}
}
...@@ -2,29 +2,29 @@ package app.insti.api; ...@@ -2,29 +2,29 @@ package app.insti.api;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import org.json.JSONObject;
import java.util.List; import java.util.List;
import app.insti.api.model.EventCreateRequest; import app.insti.api.request.EventCreateRequest;
import app.insti.api.model.EventCreateResponse; import app.insti.api.response.EventCreateResponse;
import app.insti.api.model.ExploreResponse; import app.insti.api.response.ExploreResponse;
import app.insti.api.model.ImageUploadRequest; import app.insti.api.request.ImageUploadRequest;
import app.insti.api.model.ImageUploadResponse; import app.insti.api.response.ImageUploadResponse;
import app.insti.api.model.LoginResponse; import app.insti.api.response.LoginResponse;
import app.insti.api.model.NewsFeedResponse; import app.insti.api.response.NewsFeedResponse;
import app.insti.data.Event; import app.insti.api.request.UserFCMPatchRequest;
import app.insti.data.HostelMessMenu; import app.insti.api.model.Event;
import app.insti.data.NewsArticle; import app.insti.api.model.HostelMessMenu;
import app.insti.data.Notification; import app.insti.api.model.NewsArticle;
import app.insti.data.PlacementBlogPost; import app.insti.api.model.Notification;
import app.insti.data.TrainingBlogPost; import app.insti.api.model.PlacementBlogPost;
import app.insti.data.User; import app.insti.api.model.TrainingBlogPost;
import app.insti.data.Venue; import app.insti.api.model.User;
import app.insti.api.model.Venue;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.http.Body; import retrofit2.http.Body;
import retrofit2.http.GET; import retrofit2.http.GET;
import retrofit2.http.Header; import retrofit2.http.Header;
import retrofit2.http.PATCH;
import retrofit2.http.POST; import retrofit2.http.POST;
import retrofit2.http.Path; import retrofit2.http.Path;
import retrofit2.http.Query; import retrofit2.http.Query;
...@@ -64,10 +64,10 @@ public interface RetrofitInterface { ...@@ -64,10 +64,10 @@ public interface RetrofitInterface {
Call<User> getUser(@Header("Cookie") String sessionId, @Path("uuid") String uuid); Call<User> getUser(@Header("Cookie") String sessionId, @Path("uuid") String uuid);
@GET("bodies/{uuid}") @GET("bodies/{uuid}")
Call<app.insti.data.Body> getBody(@Header("Cookie") String sessionId, @Path("uuid") String uuid); Call<app.insti.api.model.Body> getBody(@Header("Cookie") String sessionId, @Path("uuid") String uuid);
@GET("bodies") @GET("bodies")
Call<List<app.insti.data.Body>> getAllBodies(@Header("Cookie") String sessionId); Call<List<app.insti.api.model.Body>> getAllBodies(@Header("Cookie") String sessionId);
@GET("bodies/{bodyID}/follow") @GET("bodies/{bodyID}/follow")
Call<Void> updateBodyFollowing(@Header("Cookie") String sessionID, @Path("bodyID") String eventID, @Query("action") int action); Call<Void> updateBodyFollowing(@Header("Cookie") String sessionID, @Path("bodyID") String eventID, @Query("action") int action);
...@@ -78,8 +78,8 @@ public interface RetrofitInterface { ...@@ -78,8 +78,8 @@ public interface RetrofitInterface {
@GET("user-me") @GET("user-me")
Call<User> getUserMe(@Header("Cookie") String sessionID); Call<User> getUserMe(@Header("Cookie") String sessionID);
@GET("user-me") @PATCH("user-me")
Call<User> getUserMe(@Header("Cookie") String sessionID, @Query("fcm_id") String fcmId); Call<User> patchUserMe(@Header("Cookie") String sessionID, @Body UserFCMPatchRequest userFCMPatchRequest);
@GET("user-me/ues/{eventID}") @GET("user-me/ues/{eventID}")
Call<Void> updateUserEventStatus(@Header("Cookie") String sessionID, @Path("eventID") String eventID, @Query("status") int status); Call<Void> updateUserEventStatus(@Header("Cookie") String sessionID, @Path("eventID") String eventID, @Query("status") int status);
...@@ -100,7 +100,7 @@ public interface RetrofitInterface { ...@@ -100,7 +100,7 @@ public interface RetrofitInterface {
Call<List<Notification>> getNotifications(@Header("Cookie") String sessionID); Call<List<Notification>> getNotifications(@Header("Cookie") String sessionID);
@GET("notifications/read/{notificationID}") @GET("notifications/read/{notificationID}")
Call<Void> markNotificationRead(@Header("Cookie") String sessionID, @Path("notificationID") Integer notificationID); Call<Void> markNotificationRead(@Header("Cookie") String sessionID, @Path("notificationID") String notificationID);
@GET("logout") @GET("logout")
Call<Void> logout(@Header("Cookie") String sessionID); Call<Void> logout(@Header("Cookie") String sessionID);
......
package app.insti.api; package app.insti.api;
import android.content.Context;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor; import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit; import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.converter.gson.GsonConverterFactory;
public class ServiceGenerator { public class ServiceGenerator {
public static final String HEADER_CACHE_CONTROL = "Cache-Control";
public static final String HEADER_PRAGMA = "Pragma";
private static final String BASE_URL = "https://api.insti.app/api/"; private static final String BASE_URL = "https://api.insti.app/api/";
private Context context;
private Interceptor provideCacheInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
CacheControl cacheControl;
if (isConnected()) {
cacheControl = new CacheControl.Builder()
.maxAge(0, TimeUnit.SECONDS)
.build();
} else {
cacheControl = new CacheControl.Builder()
.maxStale(7, TimeUnit.DAYS)
.build();
}
return response.newBuilder()
.removeHeader(HEADER_PRAGMA)
.removeHeader(HEADER_CACHE_CONTROL)
.header(HEADER_CACHE_CONTROL, cacheControl.toString())
.build();
}
};
private Interceptor provideOfflineCacheInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!isConnected()) {
CacheControl cacheControl = new CacheControl.Builder()
.maxStale(7, TimeUnit.DAYS)
.build();
request = request.newBuilder()
.removeHeader(HEADER_PRAGMA)
.removeHeader(HEADER_CACHE_CONTROL)
.cacheControl(cacheControl)
.build();
}
return chain.proceed(request);
}
};
private Cache provideCache() {
Cache cache = null;
try {
cache = new Cache(new File(context.getCacheDir(), "api-cache"),
50 * 1024 * 1024); // 50 MB
} catch (Exception e) {
Log.e("cache", "Could not create Cache!");
}
return cache;
}
public boolean isConnected() {
try {
android.net.ConnectivityManager e = (android.net.ConnectivityManager) context.getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = e.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
} catch (Exception e) {}
return false;
}
private static OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder(); private static OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
private static Retrofit.Builder retrofitBuilder = new Retrofit.Builder() private static Retrofit.Builder retrofitBuilder = new Retrofit.Builder()
.baseUrl(BASE_URL) .baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create()); .addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit;
public static <S> S createService(Class<S> serviceClass) { private Retrofit retrofit;
retrofit = retrofitBuilder.client(clientBuilder.build()).build(); public RetrofitInterface retrofitInterface;
return retrofit.create(serviceClass); public ServiceGenerator(Context mContext) {
context = mContext;
retrofit = retrofitBuilder.client(
clientBuilder
.addInterceptor(provideOfflineCacheInterceptor)
.addNetworkInterceptor(provideCacheInterceptor)
.cache(provideCache())
.build()
).build();
retrofitInterface = retrofit.create(RetrofitInterface.class);
}
public RetrofitInterface getRetrofitInterface() {
return retrofitInterface;
} }
} }
package app.insti.data; package app.insti.api.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import java.util.List; import java.util.List;
@Entity(tableName = "bodies")
public class Body { public class Body {
@NonNull()
@PrimaryKey()
@ColumnInfo(name = "id")
@SerializedName("id") @SerializedName("id")
String bodyID; private String bodyID;
@ColumnInfo(name = "str_id")
@SerializedName("str_id") @SerializedName("str_id")
String bodyStrID; private String bodyStrID;
@ColumnInfo(name = "name")
@SerializedName("name") @SerializedName("name")
String bodyName; private String bodyName;
@ColumnInfo(name = "short_description")
@SerializedName("short_description") @SerializedName("short_description")
String bodyShortDescription; private String bodyShortDescription;
@ColumnInfo(name = "description")
@SerializedName("description") @SerializedName("description")
String bodyDescription; private String bodyDescription;
@ColumnInfo(name = "image_url")
@SerializedName("image_url") @SerializedName("image_url")
String bodyImageURL; private String bodyImageURL;
@ColumnInfo(name = "children")
@SerializedName("children") @SerializedName("children")
List<Body> bodyChildren; private List<Body> bodyChildren;
@ColumnInfo(name = "parents")
@SerializedName("parents") @SerializedName("parents")
List<Body> bodyParents; private List<Body> bodyParents;
@ColumnInfo(name = "events")
@SerializedName("events") @SerializedName("events")
List<Event> bodyEvents; private List<Event> bodyEvents;
@ColumnInfo(name = "followers_count")
@SerializedName("followers_count") @SerializedName("followers_count")
int bodyFollowersCount; private int bodyFollowersCount;
@ColumnInfo(name = "website_url")
@SerializedName("website_url") @SerializedName("website_url")
String bodyWebsiteURL; private String bodyWebsiteURL;
@ColumnInfo(name = "blog_url")
@SerializedName("blog_url") @SerializedName("blog_url")
String bodyBlogURL; private String bodyBlogURL;
@ColumnInfo(name = "user_follows")
@SerializedName("user_follows") @SerializedName("user_follows")
boolean bodyUserFollows; private boolean bodyUserFollows;
@ColumnInfo(name = "roles")
@SerializedName("roles") @SerializedName("roles")
List<Role> bodyRoles; private List<Role> bodyRoles;
@Ignore
public Body(@NonNull String bodyID) { public Body(@NonNull String bodyID) {
this.bodyID = bodyID; this.bodyID = bodyID;
} }
......
package app.insti.data; package app.insti.api.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import com.google.gson.Gson; import com.google.gson.Gson;
...@@ -12,62 +8,57 @@ import com.google.gson.annotations.SerializedName; ...@@ -12,62 +8,57 @@ import com.google.gson.annotations.SerializedName;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.List; import java.util.List;
@Entity(tableName = "events")
public class Event { public class Event {
@NonNull() @NonNull()
@PrimaryKey()
@ColumnInfo(name = "id")
@SerializedName("id") @SerializedName("id")
String eventID; private String eventID;
@ColumnInfo(name = "str_id")
@SerializedName("str_id") @SerializedName("str_id")
String eventStrID; private String eventStrID;
@ColumnInfo(name = "name")
@SerializedName("name") @SerializedName("name")
String eventName; private String eventName;
@ColumnInfo(name = "description")
@SerializedName("description") @SerializedName("description")
String eventDescription; private String eventDescription;
@ColumnInfo(name = "image_url")
@SerializedName("image_url") @SerializedName("image_url")
String eventImageURL; private String eventImageURL;
@ColumnInfo(name = "start_time")
@SerializedName("start_time") @SerializedName("start_time")
Timestamp eventStartTime; private Timestamp eventStartTime;
@ColumnInfo(name = "end_time")
@SerializedName("end_time") @SerializedName("end_time")
Timestamp eventEndTime; private Timestamp eventEndTime;
@ColumnInfo(name = "all_day")
@SerializedName("all_day") @SerializedName("all_day")
boolean allDayEvent; private boolean allDayEvent;
@ColumnInfo(name = "venues")
@SerializedName("venues") @SerializedName("venues")
List<Venue> eventVenues; private List<Venue> eventVenues;
@ColumnInfo(name = "bodies")
@SerializedName("bodies") @SerializedName("bodies")
List<Body> eventBodies; private List<Body> eventBodies;
@ColumnInfo(name = "interested_count")
@SerializedName("interested_count") @SerializedName("interested_count")
int eventInterestedCount; private int eventInterestedCount;
@ColumnInfo(name = "going_count")
@SerializedName("going_count") @SerializedName("going_count")
int eventGoingCount; private int eventGoingCount;
@ColumnInfo(name = "interested")
@SerializedName("interested") @SerializedName("interested")
List<User> eventInterested; private List<User> eventInterested;
@ColumnInfo(name = "going")
@SerializedName("going") @SerializedName("going")
List<User> eventGoing; private List<User> eventGoing;
@ColumnInfo(name = "website_url")
@SerializedName("website_url") @SerializedName("website_url")
String eventWebsiteURL; private String eventWebsiteURL;
@ColumnInfo(name = "user_ues")
@SerializedName("user_ues") @SerializedName("user_ues")
int eventUserUes; private int eventUserUes;
@Ignore private boolean eventBigImage = false;
boolean eventBigImage = false;
public Event(String eventID, String eventStrID, String eventName, String eventDescription, String eventImageURL, Timestamp eventStartTime, Timestamp eventEndTime, boolean allDayEvent, List<Venue> eventVenues, List<Body> eventBodies, int eventInterestedCount, int eventGoingCount, List<User> eventInterested, List<User> eventGoing, String eventWebsiteURL, int eventUserUes) { public Event(String eventID, String eventStrID, String eventName, String eventDescription, String eventImageURL, Timestamp eventStartTime, Timestamp eventEndTime, boolean allDayEvent, List<Venue> eventVenues, List<Body> eventBodies, int eventInterestedCount, int eventGoingCount, List<User> eventInterested, List<User> eventGoing, String eventWebsiteURL, int eventUserUes) {
this.eventID = eventID; this.eventID = eventID;
...@@ -121,6 +112,10 @@ public class Event { ...@@ -121,6 +112,10 @@ public class Event {
} }
public String getEventImageURL() { public String getEventImageURL() {
// Fallback to body image if event has no image
if (eventImageURL == null) {
return getEventBodies().get(0).getBodyImageURL();
}
return eventImageURL; return eventImageURL;
} }
......
package app.insti.data; package app.insti.api.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import java.util.List; import java.util.List;
@Entity(tableName = "hostelMessMenus")
public class HostelMessMenu { public class HostelMessMenu {
@NonNull() @NonNull()
@PrimaryKey()
@ColumnInfo(name = "id")
@SerializedName("id") @SerializedName("id")
private String menuID; private String menuID;
@ColumnInfo(name = "name")
@SerializedName("name") @SerializedName("name")
private String name; private String name;
@ColumnInfo(name = "short_name")
@SerializedName("short_name") @SerializedName("short_name")
private String shortName; private String shortName;
@ColumnInfo(name = "long_name")
@SerializedName("long_name") @SerializedName("long_name")
private String longName; private String longName;
@ColumnInfo(name = "mess")
@SerializedName("mess") @SerializedName("mess")
private List<MessMenu> messMenus; private List<MessMenu> messMenus;
......
package app.insti.data; package app.insti.api.model;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
public class MessMenu { public class MessMenu {
@NonNull() @NonNull()
@PrimaryKey()
@SerializedName("id") @SerializedName("id")
private String mealID; private String mealID;
......
package app.insti.data; package app.insti.api.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import java.sql.Timestamp; import java.sql.Timestamp;
@Entity(tableName = "news") import app.insti.interfaces.Browsable;
public class NewsArticle { public class NewsArticle implements Browsable {
@NonNull() @NonNull()
@PrimaryKey()
@ColumnInfo(name = "id")
@SerializedName("id") @SerializedName("id")
private String articleID; private String articleID;
@ColumnInfo(name = "link")
@SerializedName("link") @SerializedName("link")
private String link; private String link;
@ColumnInfo(name = "title")
@SerializedName("title") @SerializedName("title")
private String title; private String title;
@ColumnInfo(name = "content")
@SerializedName("content") @SerializedName("content")
private String content; private String content;
@ColumnInfo(name = "published")
@SerializedName("published") @SerializedName("published")
private Timestamp published; private Timestamp published;
@ColumnInfo(name = "body")
@SerializedName("body") @SerializedName("body")
private Body body; private Body body;
......
package app.insti.data; package app.insti.api.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@Entity(tableName = "news")
public class Notification { public class Notification {
@NonNull() @NonNull()
@PrimaryKey()
@ColumnInfo(name = "id")
@SerializedName("id") @SerializedName("id")
private Integer notificationId; private Integer notificationId;
@ColumnInfo(name = "verb")
@SerializedName("verb") @SerializedName("verb")
private String notificationVerb; private String notificationVerb;
@ColumnInfo(name = "unread")
@SerializedName("unread") @SerializedName("unread")
private boolean notificationUnread; private boolean notificationUnread;
@ColumnInfo(name = "actor_type")
@SerializedName("actor_type") @SerializedName("actor_type")
private String notificationActorType; private String notificationActorType;
@ColumnInfo(name = "actor")
@SerializedName("actor") @SerializedName("actor")
private Object notificationActor; private Object notificationActor;
......
package app.insti.data; package app.insti.api.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import java.sql.Timestamp; import java.sql.Timestamp;
@Entity(tableName = "placementBlogPosts") import app.insti.interfaces.Browsable;
public class PlacementBlogPost { public class PlacementBlogPost implements Browsable {
@NonNull() @NonNull()
@PrimaryKey()
@ColumnInfo(name = "id")
@SerializedName("id") @SerializedName("id")
private String postID; private String postID;
@ColumnInfo(name = "link")
@SerializedName("link") @SerializedName("link")
private String link; private String link;
@ColumnInfo(name = "title")
@SerializedName("title") @SerializedName("title")
private String title; private String title;
@ColumnInfo(name = "content")
@SerializedName("content") @SerializedName("content")
private String content; private String content;
@ColumnInfo(name = "published")
@SerializedName("published") @SerializedName("published")
private Timestamp published; private Timestamp published;
......
package app.insti.data; package app.insti.api.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import java.util.List; import java.util.List;
@Entity(tableName = "roles")
public class Role { public class Role {
@NonNull() @NonNull()
@PrimaryKey()
@ColumnInfo(name = "id")
@SerializedName("id") @SerializedName("id")
String roleID; private String roleID;
@ColumnInfo(name = "name")
@SerializedName("name") @SerializedName("name")
String roleName; private String roleName;
@ColumnInfo(name = "inheritable")
@SerializedName("inheritable") @SerializedName("inheritable")
boolean roleInheritable; private boolean roleInheritable;
@ColumnInfo(name = "body")
@SerializedName("body") @SerializedName("body")
String roleBody; private String roleBody;
@ColumnInfo(name = "body_detail")
@SerializedName("body_detail") @SerializedName("body_detail")
Body roleBodyDetails; private Body roleBodyDetails;
@ColumnInfo(name = "bodies")
@SerializedName("bodies") @SerializedName("bodies")
List<Body> roleBodies; private List<Body> roleBodies;
@ColumnInfo(name = "permissions")
@SerializedName("permissions") @SerializedName("permissions")
List<String> rolePermissions; private List<String> rolePermissions;
@ColumnInfo(name = "users")
@SerializedName("users") @SerializedName("users")
List<String> roleUsers; private List<String> roleUsers;
@ColumnInfo(name = "users_detail")
@SerializedName("users_detail") @SerializedName("users_detail")
List<User> roleUsersDetail; private List<User> roleUsersDetail;
public Role(String roleID, String roleName, boolean roleInheritable, String roleBody, Body roleBodyDetails, List<Body> roleBodies, List<String> rolePermissions, List<String> roleUsers, List<User> roleUsersDetail) { public Role(String roleID, String roleName, boolean roleInheritable, String roleBody, Body roleBodyDetails, List<Body> roleBodies, List<String> rolePermissions, List<String> roleUsers, List<User> roleUsersDetail) {
this.roleID = roleID; this.roleID = roleID;
......
package app.insti.data; package app.insti.api.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import java.sql.Timestamp; import java.sql.Timestamp;
@Entity(tableName = "trainingBlogPosts") import app.insti.interfaces.Browsable;
public class TrainingBlogPost { public class TrainingBlogPost implements Browsable {
@NonNull() @NonNull()
@PrimaryKey()
@ColumnInfo(name = "id")
@SerializedName("id") @SerializedName("id")
private String postID; private String postID;
@ColumnInfo(name = "link")
@SerializedName("link") @SerializedName("link")
private String link; private String link;
@ColumnInfo(name = "title")
@SerializedName("title") @SerializedName("title")
private String title; private String title;
@ColumnInfo(name = "content")
@SerializedName("content") @SerializedName("content")
private String content; private String content;
@ColumnInfo(name = "published")
@SerializedName("published") @SerializedName("published")
private Timestamp published; private Timestamp published;
......
package app.insti.data; package app.insti.api.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import com.google.gson.Gson; import com.google.gson.Gson;
...@@ -11,67 +7,60 @@ import com.google.gson.annotations.SerializedName; ...@@ -11,67 +7,60 @@ import com.google.gson.annotations.SerializedName;
import java.util.List; import java.util.List;
@Entity(tableName = "users")
public class User { public class User {
@NonNull() @NonNull()
@PrimaryKey()
@ColumnInfo(name = "id")
@SerializedName("id") @SerializedName("id")
String userID; private String userID;
@ColumnInfo(name = "name")
@SerializedName("name") @SerializedName("name")
String userName; private String userName;
@ColumnInfo(name = "profile_pic")
@SerializedName("profile_pic") @SerializedName("profile_pic")
String userProfilePictureUrl; private String userProfilePictureUrl;
@ColumnInfo(name = "events_interested")
@SerializedName("events_interested") @SerializedName("events_interested")
List<Event> userInterestedEvents; private List<Event> userInterestedEvents;
@ColumnInfo(name = "events_going")
@SerializedName("events_going") @SerializedName("events_going")
List<Event> userGoingEvents; private List<Event> userGoingEvents;
@ColumnInfo(name = "email")
@SerializedName("email") @SerializedName("email")
String userEmail; private String userEmail;
@ColumnInfo(name = "roll_no")
@SerializedName("roll_no") @SerializedName("roll_no")
String userRollNumber; private String userRollNumber;
@ColumnInfo(name = "contact_no")
@SerializedName("contact_no") @SerializedName("contact_no")
String userContactNumber; private String userContactNumber;
@ColumnInfo(name = "about")
@SerializedName("about") @SerializedName("about")
String userAbout; private String userAbout;
@ColumnInfo(name = "followed_bodies")
@SerializedName("followed_bodies") @SerializedName("followed_bodies")
List<Body> userFollowedBodies; private List<Body> userFollowedBodies;
@ColumnInfo(name = "followed_bodies_id")
@SerializedName("followed_bodies_id") @SerializedName("followed_bodies_id")
List<String> userFollowedBodiesID; private List<String> userFollowedBodiesID;
@ColumnInfo(name = "roles")
@SerializedName("roles") @SerializedName("roles")
List<Role> userRoles; private List<Role> userRoles;
@ColumnInfo(name = "institute_roles")
@SerializedName("institute_roles") @SerializedName("institute_roles")
List<Role> userInstituteRoles; private List<Role> userInstituteRoles;
@ColumnInfo(name = "former_roles")
@SerializedName("former_roles") @SerializedName("former_roles")
List<Role> userFormerRoles; private List<Role> userFormerRoles;
@ColumnInfo(name = "website_url")
@SerializedName("website_url") @SerializedName("website_url")
String userWebsiteURL; private String userWebsiteURL;
@ColumnInfo(name = "ldap_id")
@SerializedName("ldap_id") @SerializedName("ldap_id")
String userLDAPId; private String userLDAPId;
@ColumnInfo(name = "hostel")
@SerializedName("hostel") @SerializedName("hostel")
String hostel; private String hostel;
/** private String currentRole;
* Not in database
*/
@Ignore
String currentRole;
public User(@NonNull String userID, String userName, String userProfilePictureUrl, List<Event> userInterestedEvents, List<Event> userGoingEvents, String userEmail, String userRollNumber, String userContactNumber, String userAbout, List<Body> userFollowedBodies, List<String> userFollowedBodiesID, List<Role> userRoles, List<Role> userInstituteRoles, List<Role> userFormerRoles, String userWebsiteURL, String userLDAPId, String hostel) { public User(@NonNull String userID, String userName, String userProfilePictureUrl, List<Event> userInterestedEvents, List<Event> userGoingEvents, String userEmail, String userRollNumber, String userContactNumber, String userAbout, List<Body> userFollowedBodies, List<String> userFollowedBodiesID, List<Role> userRoles, List<Role> userInstituteRoles, List<Role> userFormerRoles, String userWebsiteURL, String userLDAPId, String hostel) {
this.userID = userID; this.userID = userID;
......
package app.insti.data; package app.insti.api.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
@Entity(tableName = "venues")
public class Venue { public class Venue {
@NonNull() @NonNull()
@PrimaryKey()
@ColumnInfo(name = "id")
@SerializedName("id") @SerializedName("id")
String venueID; private String venueID;
@ColumnInfo(name = "name")
@SerializedName("name") @SerializedName("name")
String venueName; private String venueName;
@ColumnInfo(name = "short_name")
@SerializedName("short_name") @SerializedName("short_name")
String venueShortName; private String venueShortName;
@ColumnInfo(name = "description")
@SerializedName("description") @SerializedName("description")
String venueDescripion; private String venueDescripion;
@ColumnInfo(name = "parent")
@SerializedName("parent") @SerializedName("parent")
String venueParentId; private String venueParentId;
@ColumnInfo(name = "parent_relation")
@SerializedName("parent_relation") @SerializedName("parent_relation")
String venueParentRelation; private String venueParentRelation;
@ColumnInfo(name = "group_id")
@SerializedName("group_id") @SerializedName("group_id")
Integer venueGroupId; private Integer venueGroupId;
@ColumnInfo(name = "pixel_x")
@SerializedName("pixel_x") @SerializedName("pixel_x")
Integer venuePixelX; private Integer venuePixelX;
@ColumnInfo(name = "pixel_y")
@SerializedName("pixel_y") @SerializedName("pixel_y")
Integer venuePixelY; private Integer venuePixelY;
@ColumnInfo(name = "reusable")
@SerializedName("reusable") @SerializedName("reusable")
Boolean venueReusable; private Boolean venueReusable;
@ColumnInfo(name = "lat")
@SerializedName("lat") @SerializedName("lat")
double venueLatitude; private double venueLatitude;
@ColumnInfo(name = "lng")
@SerializedName("lng") @SerializedName("lng")
double venueLongitude; private double venueLongitude;
public Venue(String venueID, String venueName, String venueShortName, String venueDescripion, String venueParentId, String venueParentRelation, Integer venueGroupId, Integer venuePixelX, Integer venuePixelY, Boolean venueReusable, double venueLatitude, double venueLongitude) { public Venue(String venueID, String venueName, String venueShortName, String venueDescripion, String venueParentId, String venueParentRelation, Integer venueGroupId, Integer venuePixelX, Integer venuePixelY, Boolean venueReusable, double venueLatitude, double venueLongitude) {
this.venueID = venueID; this.venueID = venueID;
......
package app.insti.api.model; package app.insti.api.request;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
......
package app.insti.api.model; package app.insti.api.request;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
......
package app.insti.api.request;
import com.google.gson.annotations.SerializedName;
public class UserFCMPatchRequest {
@SerializedName("fcm_id")
private String userFCMId;
@SerializedName("android_version")
private int userAndroidVersion;
public UserFCMPatchRequest(String userFCMId, int userAndroidVersion) {
this.userFCMId = userFCMId;
this.userAndroidVersion = userAndroidVersion;
}
}
package app.insti.api.model; package app.insti.api.response;
/** /**
* Created by mrunz on 15/7/17. * Created by mrunz on 15/7/17.
......
package app.insti.api.model; package app.insti.api.response;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import java.util.List; import java.util.List;
import app.insti.data.Body; import app.insti.api.model.Body;
import app.insti.data.Event; import app.insti.api.model.Event;
import app.insti.data.User; import app.insti.api.model.User;
public class ExploreResponse { public class ExploreResponse {
@SerializedName("bodies") @SerializedName("bodies")
......
package app.insti.api.model; package app.insti.api.response;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
......
package app.insti.api.model; package app.insti.api.response;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import app.insti.data.User; import app.insti.api.model.User;
public class LoginResponse { public class LoginResponse {
@SerializedName("sessionid") @SerializedName("sessionid")
......
package app.insti.api.model; package app.insti.api.response;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import java.util.List; import java.util.List;
import app.insti.data.Event; import app.insti.api.model.Event;
public class NewsFeedResponse { public class NewsFeedResponse {
@SerializedName("data") @SerializedName("data")
......
package app.insti.data;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.TypeConverters;
import android.content.Context;
@Database(entities = {Event.class, Body.class, Venue.class, User.class, Role.class, PlacementBlogPost.class, TrainingBlogPost.class, HostelMessMenu.class, NewsArticle.class}, version = 2, exportSchema = false)
@TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase INSTANCE;
public static AppDatabase getAppDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "database")
// allow queries on the main thread.
// Don't do this on a real app! See PersistenceBasicSample for an example.
// .allowMainThreadQueries()
.fallbackToDestructiveMigration()
.build();
}
return INSTANCE;
}
public static void destroyInstance() {
INSTANCE = null;
}
public abstract DbDao dbDao();
}
package app.insti.data;
import android.arch.persistence.room.TypeConverter;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.sql.Timestamp;
import java.util.List;
public class Converters {
@TypeConverter
public static List<Event> eventsfromString(String value) {
Type listType = new TypeToken<List<Event>>() {
}.getType();
return new Gson().fromJson(value, listType);
}
@TypeConverter
public static String stringfromEvents(List<Event> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
return json;
}
@TypeConverter
public static List<User> usersfromString(String value) {
Type listType = new TypeToken<List<User>>() {
}.getType();
return new Gson().fromJson(value, listType);
}
@TypeConverter
public static String stringfromUsers(List<User> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
return json;
}
@TypeConverter
public static List<Venue> venuesfromString(String value) {
Type listType = new TypeToken<List<Venue>>() {
}.getType();
return new Gson().fromJson(value, listType);
}
@TypeConverter
public static String stringfromVenues(List<Venue> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
return json;
}
@TypeConverter
public static List<Body> bodiesfromString(String value) {
Type listType = new TypeToken<List<Body>>() {
}.getType();
return new Gson().fromJson(value, listType);
}
@TypeConverter
public static String stringfromBodies(List<Body> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
return json;
}
@TypeConverter
public static List<Role> rolesfromString(String value) {
Type listType = new TypeToken<List<Role>>() {
}.getType();
return new Gson().fromJson(value, listType);
}
@TypeConverter
public static String stringfromRoles(List<Role> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
return json;
}
@TypeConverter
public static Timestamp timestampfromString(String value) {
try {
return new Gson().fromJson(value, Timestamp.class);
} catch (JsonSyntaxException e) {
Log.d("Converters", "timestampfromString: " + value);
e.printStackTrace();
return null;
}
}
@TypeConverter
public static String stringfromTimestamp(Timestamp timestamp) {
Gson gson = new Gson();
String json = gson.toJson(timestamp);
return json;
}
@TypeConverter
public static Body bodyfromString(String value) {
Type listType = new TypeToken<Body>() {
}.getType();
return new Gson().fromJson(value, listType);
}
@TypeConverter
public static String stringfromBody(Body body) {
Gson gson = new Gson();
String json = gson.toJson(body);
return json;
}
@TypeConverter
public static Object objectFromString(String value) {
Type listType = new TypeToken<Object>() {
}.getType();
return new Gson().fromJson(value, listType);
}
@TypeConverter
public static String stringFromObject(Object object) {
Gson gson = new Gson();
String json = gson.toJson(object);
return json;
}
@TypeConverter
public static List<String> stringsfromString(String value) {
Type listType = new TypeToken<List<String>>() {
}.getType();
return new Gson().fromJson(value, listType);
}
@TypeConverter
public static String stringfromStrings(List<String> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
return json;
}
@TypeConverter
public static List<MessMenu> messMenusfromString(String value) {
Type listType = new TypeToken<List<MessMenu>>() {
}.getType();
return new Gson().fromJson(value, listType);
}
@TypeConverter
public static String stringfromMessMenus(List<MessMenu> list) {
Gson gson = new Gson();
String json = gson.toJson(list);
return json;
}
}
\ No newline at end of file
package app.insti.data;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;
import java.util.List;
@Dao
public interface DbDao {
@Query("SELECT * FROM events")
List<Event> getAllEvents();
@Query("SELECT * FROM events WHERE user_ues <> 0")
List<Event> getFollowingEvents();
@Query("SELECT * FROM bodies")
List<Body> getAllBodies();
@Query("SELECT * FROM venues")
List<Venue> getAllVenues();
@Query("SELECT * FROM users")
List<User> getAllUsers();
@Query("SELECT * FROM roles")
List<Role> getAllRoles();
@Query("SELECT * FROM placementBlogPosts")
List<PlacementBlogPost> getAllPlacementBlogPosts();
@Query("SELECT * FROM trainingBlogPosts")
List<TrainingBlogPost> getAllTrainingBlogPosts();
@Query("SELECT * FROM hostelMessMenus")
List<HostelMessMenu> getAllHostelMessMenus();
@Query("SELECT * FROM news")
List<NewsArticle> getAllNewsArticles();
@Query("SELECT COUNT(*) from events")
int countEvents();
@Query("SELECT * FROM bodies WHERE id == :id")
public Body[] getBody(String id);
@Query("SELECT COUNT(*) from venues")
int countVenues();
@Query("SELECT COUNT(*) from bodies")
int countBodies();
@Query("SELECT COUNT(*) from users")
int countUsers();
@Query("SELECT COUNT(*) from roles")
int countRoles();
@Query("SELECT COUNT(*) from hostelMessMenus")
int countHostelMessMenus();
@Insert
void insertEvents(List<Event> events);
@Insert
void insertEvent(Event event);
@Update
void updateEvent(Event event);
@Insert
void insertBodies(List<Body> bodies);
@Insert
void insertBody(Body body);
@Update
void updateBody(Body body);
@Insert
void insertVenues(List<Venue> venues);
@Insert
void insertVenue(Venue venue);
@Insert
void insertUsers(List<User> users);
@Insert
void insertUser(User user);
@Insert
void insertRoles(List<Role> roles);
@Insert
void insertRole(Role role);
@Insert
void insertPlacementBlogPost(PlacementBlogPost post);
@Insert
void insertPlacementBlogPosts(List<PlacementBlogPost> posts);
@Insert
void insertTrainingBlogPost(TrainingBlogPost post);
@Insert
void insertTrainingBlogPosts(List<TrainingBlogPost> posts);
@Insert
void insertHostelMessMenu(HostelMessMenu hostelMessMenu);
@Insert
void insertHostelMessMenus(List<HostelMessMenu> hostelMessMenus);
@Insert
void insertNewsArticle(NewsArticle newsArticle);
@Insert
void insertNewsArticles(List<NewsArticle> newsArticles);
@Delete
void deleteEvent(Event event);
@Delete
void deleteVenue(Venue venue);
@Delete
void deleteBody(Body body);
@Delete
void deleteUser(User user);
@Delete
void deleteRole(Role role);
@Query("DELETE from events")
void deleteEvents();
@Query("DELETE from venues")
void deleteVenues();
@Query("DELETE from bodies")
void deleteBodies();
@Query("DELETE from users")
void deleteUsers();
@Query("DELETE from roles")
void deleteRoles();
@Query("DELETE from placementBlogPosts")
void deletePlacementBlogPosts();
@Query("DELETE from trainingBlogPosts")
void deleteTrainingBlogPosts();
@Query("DELETE from hostelMessMenus")
void deleteHostelMessMenus();
@Query("DELETE from news")
void deleteNewsArticles();
}
...@@ -28,9 +28,8 @@ import app.insti.Constants; ...@@ -28,9 +28,8 @@ import app.insti.Constants;
import app.insti.R; import app.insti.R;
import app.insti.activity.MainActivity; import app.insti.activity.MainActivity;
import app.insti.api.RetrofitInterface; import app.insti.api.RetrofitInterface;
import app.insti.api.ServiceGenerator; import app.insti.api.model.Body;
import app.insti.data.Body; import app.insti.api.model.Event;
import app.insti.data.Event;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
...@@ -167,7 +166,7 @@ public class AddEventFragment extends BaseFragment { ...@@ -167,7 +166,7 @@ public class AddEventFragment extends BaseFragment {
if (url.contains("/event/")) { if (url.contains("/event/")) {
url = url.substring(url.lastIndexOf("/") + 1); url = url.substring(url.lastIndexOf("/") + 1);
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.getEvent(((MainActivity) getActivity()).getSessionIDHeader(), url).enqueue(new Callback<Event>() { retrofitInterface.getEvent(((MainActivity) getActivity()).getSessionIDHeader(), url).enqueue(new Callback<Event>() {
@Override @Override
public void onResponse(Call<Event> call, Response<Event> response) { public void onResponse(Call<Event> call, Response<Event> response) {
...@@ -185,7 +184,7 @@ public class AddEventFragment extends BaseFragment { ...@@ -185,7 +184,7 @@ public class AddEventFragment extends BaseFragment {
} else if (url.contains("/org/")) { } else if (url.contains("/org/")) {
url = url.substring(url.lastIndexOf("/") + 1); url = url.substring(url.lastIndexOf("/") + 1);
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.getBody(((MainActivity) getActivity()).getSessionIDHeader(), url).enqueue(new Callback<Body>() { retrofitInterface.getBody(((MainActivity) getActivity()).getSessionIDHeader(), url).enqueue(new Callback<Body>() {
@Override @Override
public void onResponse(Call<Body> call, Response<Body> response) { public void onResponse(Call<Body> call, Response<Body> response) {
......
...@@ -10,7 +10,6 @@ import android.graphics.Color; ...@@ -10,7 +10,6 @@ import android.graphics.Color;
import android.graphics.Point; import android.graphics.Point;
import android.graphics.Rect; import android.graphics.Rect;
import android.net.Uri; import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.support.design.widget.FloatingActionButton; import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
...@@ -37,7 +36,7 @@ import java.util.ArrayList; ...@@ -37,7 +36,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import app.insti.Constants; import app.insti.Constants;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.ShareURLMaker; import app.insti.ShareURLMaker;
import app.insti.activity.MainActivity; import app.insti.activity.MainActivity;
...@@ -45,12 +44,10 @@ import app.insti.adapter.BodyAdapter; ...@@ -45,12 +44,10 @@ import app.insti.adapter.BodyAdapter;
import app.insti.adapter.FeedAdapter; import app.insti.adapter.FeedAdapter;
import app.insti.adapter.UserAdapter; import app.insti.adapter.UserAdapter;
import app.insti.api.RetrofitInterface; import app.insti.api.RetrofitInterface;
import app.insti.api.ServiceGenerator; import app.insti.api.model.Body;
import app.insti.data.AppDatabase; import app.insti.api.model.Event;
import app.insti.data.Body; import app.insti.api.model.Role;
import app.insti.data.Event; import app.insti.api.model.User;
import app.insti.data.Role;
import app.insti.data.User;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
...@@ -67,7 +64,6 @@ public class BodyFragment extends BackHandledFragment { ...@@ -67,7 +64,6 @@ public class BodyFragment extends BackHandledFragment {
String TAG = "BodyFragment"; String TAG = "BodyFragment";
private AppDatabase appDatabase;
// TODO: Rename and change types of parameters // TODO: Rename and change types of parameters
private Body min_body; private Body min_body;
private SwipeRefreshLayout bodySwipeRefreshLayout; private SwipeRefreshLayout bodySwipeRefreshLayout;
...@@ -133,15 +129,10 @@ public class BodyFragment extends BackHandledFragment { ...@@ -133,15 +129,10 @@ public class BodyFragment extends BackHandledFragment {
/* Initialize */ /* Initialize */
bodyDisplayed = false; bodyDisplayed = false;
appDatabase = AppDatabase.getAppDatabase(getContext());
body = min_body; body = min_body;
displayBody(); displayBody();
/* Check if full body was passed */ updateBody();
if (min_body.getBodyDescription() == null) {
new getDbBody().execute(min_body.getBodyID());
updateBody();
}
bodySwipeRefreshLayout = getActivity().findViewById(R.id.body_swipe_refresh_layout); bodySwipeRefreshLayout = getActivity().findViewById(R.id.body_swipe_refresh_layout);
bodySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { bodySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
...@@ -157,15 +148,13 @@ public class BodyFragment extends BackHandledFragment { ...@@ -157,15 +148,13 @@ public class BodyFragment extends BackHandledFragment {
} }
private void updateBody() { private void updateBody() {
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.getBody(((MainActivity) getActivity()).getSessionIDHeader(), min_body.getBodyID()).enqueue(new Callback<Body>() { retrofitInterface.getBody(((MainActivity) getActivity()).getSessionIDHeader(), min_body.getBodyID()).enqueue(new Callback<Body>() {
@Override @Override
public void onResponse(Call<Body> call, Response<Body> response) { public void onResponse(Call<Body> call, Response<Body> response) {
if (response.isSuccessful()) { if (response.isSuccessful()) {
Body bodyResponse = response.body(); Body bodyResponse = response.body();
new updateDbBody().execute(bodyResponse);
if (!bodyDisplayed) { if (!bodyDisplayed) {
body = bodyResponse; body = bodyResponse;
displayBody(); displayBody();
...@@ -236,16 +225,13 @@ public class BodyFragment extends BackHandledFragment { ...@@ -236,16 +225,13 @@ public class BodyFragment extends BackHandledFragment {
followButton.setOnClickListener(new View.OnClickListener() { followButton.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.updateBodyFollowing(((MainActivity) getActivity()).getSessionIDHeader(), body.getBodyID(), body.getBodyUserFollows() ? 0 : 1).enqueue(new Callback<Void>() { retrofitInterface.updateBodyFollowing(((MainActivity) getActivity()).getSessionIDHeader(), body.getBodyID(), body.getBodyUserFollows() ? 0 : 1).enqueue(new Callback<Void>() {
@Override @Override
public void onResponse(Call<Void> call, Response<Void> response) { public void onResponse(Call<Void> call, Response<Void> response) {
if (response.isSuccessful()) { if (response.isSuccessful()) {
body.setBodyUserFollows(!body.getBodyUserFollows()); body.setBodyUserFollows(!body.getBodyUserFollows());
body.setBodyFollowersCount(body.getBodyUserFollows()? body.getBodyFollowersCount()+1:body.getBodyFollowersCount()-1);
new updateDbBody().execute(body);
followButton.setBackgroundColor(getResources().getColor(body.getBodyUserFollows() ? R.color.colorAccent : R.color.colorWhite)); followButton.setBackgroundColor(getResources().getColor(body.getBodyUserFollows() ? R.color.colorAccent : R.color.colorWhite));
followButton.setText( EventFragment.getCountBadgeSpannable("FOLLOW", body.getBodyFollowersCount()) );
} }
} }
...@@ -546,31 +532,4 @@ public class BodyFragment extends BackHandledFragment { ...@@ -546,31 +532,4 @@ public class BodyFragment extends BackHandledFragment {
startScaleFinal = startScale; startScaleFinal = startScale;
zoomMode = true; zoomMode = true;
} }
private class updateDbBody extends AsyncTask<Body, Void, Integer> {
@Override
protected Integer doInBackground(Body... body) {
if (appDatabase.dbDao().getBody(body[0].getBodyID()).length > 0) {
appDatabase.dbDao().updateBody(body[0]);
} else {
appDatabase.dbDao().insertBody(body[0]);
}
return 1;
}
}
private class getDbBody extends AsyncTask<String, Void, Body[]> {
@Override
protected Body[] doInBackground(String... id) {
return appDatabase.dbDao().getBody(min_body.getBodyID());
}
@Override
protected void onPostExecute(Body[] result) {
if (result.length > 0 && !bodyDisplayed) {
body = result[0];
displayBody();
}
}
}
} }
...@@ -16,10 +16,10 @@ import com.google.gson.reflect.TypeToken; ...@@ -16,10 +16,10 @@ import com.google.gson.reflect.TypeToken;
import java.util.List; import java.util.List;
import app.insti.Constants; import app.insti.Constants;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.adapter.BodyAdapter; import app.insti.adapter.BodyAdapter;
import app.insti.data.Body; import app.insti.api.model.Body;
/** /**
* A simple {@link Fragment} subclass. * A simple {@link Fragment} subclass.
......
...@@ -28,14 +28,13 @@ import java.util.List; ...@@ -28,14 +28,13 @@ import java.util.List;
import java.util.TimeZone; import java.util.TimeZone;
import app.insti.Constants; import app.insti.Constants;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.activity.MainActivity; import app.insti.activity.MainActivity;
import app.insti.adapter.FeedAdapter; import app.insti.adapter.FeedAdapter;
import app.insti.api.RetrofitInterface; import app.insti.api.RetrofitInterface;
import app.insti.api.ServiceGenerator; import app.insti.api.response.NewsFeedResponse;
import app.insti.api.model.NewsFeedResponse; import app.insti.api.model.Event;
import app.insti.data.Event;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
...@@ -117,7 +116,7 @@ public class CalendarFragment extends BaseFragment { ...@@ -117,7 +116,7 @@ public class CalendarFragment extends BaseFragment {
final String oneMonthBack = isoFormatter.format(oneMonthBackDate).toString(); final String oneMonthBack = isoFormatter.format(oneMonthBackDate).toString();
final String oneMonthOn = isoFormatter.format(oneMonthOnDate).toString(); final String oneMonthOn = isoFormatter.format(oneMonthOnDate).toString();
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.getEventsBetweenDates(((MainActivity) getActivity()).getSessionIDHeader(), oneMonthBack, oneMonthOn).enqueue(new Callback<NewsFeedResponse>() { retrofitInterface.getEventsBetweenDates(((MainActivity) getActivity()).getSessionIDHeader(), oneMonthBack, oneMonthOn).enqueue(new Callback<NewsFeedResponse>() {
@Override @Override
public void onResponse(Call<NewsFeedResponse> call, Response<NewsFeedResponse> response) { public void onResponse(Call<NewsFeedResponse> call, Response<NewsFeedResponse> response) {
......
...@@ -10,7 +10,6 @@ import android.graphics.Color; ...@@ -10,7 +10,6 @@ import android.graphics.Color;
import android.graphics.Point; import android.graphics.Point;
import android.graphics.Rect; import android.graphics.Rect;
import android.net.Uri; import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.support.design.widget.FloatingActionButton; import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
...@@ -43,17 +42,15 @@ import java.util.Date; ...@@ -43,17 +42,15 @@ import java.util.Date;
import java.util.List; import java.util.List;
import app.insti.Constants; import app.insti.Constants;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.ShareURLMaker; import app.insti.ShareURLMaker;
import app.insti.activity.MainActivity; import app.insti.activity.MainActivity;
import app.insti.adapter.BodyAdapter; import app.insti.adapter.BodyAdapter;
import app.insti.api.RetrofitInterface; import app.insti.api.RetrofitInterface;
import app.insti.api.ServiceGenerator; import app.insti.api.model.Body;
import app.insti.data.AppDatabase; import app.insti.api.model.Event;
import app.insti.data.Body; import app.insti.api.model.Venue;
import app.insti.data.Event;
import app.insti.data.Venue;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
...@@ -71,7 +68,6 @@ public class EventFragment extends BackHandledFragment { ...@@ -71,7 +68,6 @@ public class EventFragment extends BackHandledFragment {
ImageButton shareEventButton; ImageButton shareEventButton;
RecyclerView bodyRecyclerView; RecyclerView bodyRecyclerView;
String TAG = "EventFragment"; String TAG = "EventFragment";
private AppDatabase appDatabase;
// Hold a reference to the current animator, // Hold a reference to the current animator,
// so that it can be canceled mid-way. // so that it can be canceled mid-way.
...@@ -135,9 +131,6 @@ public class EventFragment extends BackHandledFragment { ...@@ -135,9 +131,6 @@ public class EventFragment extends BackHandledFragment {
public void onStart() { public void onStart() {
super.onStart(); super.onStart();
/* Initialize */
appDatabase = AppDatabase.getAppDatabase(getContext());
Bundle bundle = getArguments(); Bundle bundle = getArguments();
String eventJson = bundle.getString(Constants.EVENT_JSON); String eventJson = bundle.getString(Constants.EVENT_JSON);
Log.d(TAG, "onStart: " + eventJson); Log.d(TAG, "onStart: " + eventJson);
...@@ -161,11 +154,6 @@ public class EventFragment extends BackHandledFragment { ...@@ -161,11 +154,6 @@ public class EventFragment extends BackHandledFragment {
webEventButton = getActivity().findViewById(R.id.web_event_button); webEventButton = getActivity().findViewById(R.id.web_event_button);
shareEventButton = getActivity().findViewById(R.id.share_event_button); shareEventButton = getActivity().findViewById(R.id.share_event_button);
// Fallback to image of first body if event has no image
if (event.getEventImageURL() == null) {
event.setEventImageURL(event.getEventBodies().get(0).getBodyImageURL());
}
Picasso.get().load(event.getEventImageURL()).into(eventPicture); Picasso.get().load(event.getEventImageURL()).into(eventPicture);
eventTitle.setText(event.getEventName()); eventTitle.setText(event.getEventName());
Markwon.setMarkdown(eventDescription, event.getEventDescription()); Markwon.setMarkdown(eventDescription, event.getEventDescription());
...@@ -299,7 +287,7 @@ public class EventFragment extends BackHandledFragment { ...@@ -299,7 +287,7 @@ public class EventFragment extends BackHandledFragment {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
final int endStatus = event.getEventUserUes() == status ? 0 : status; final int endStatus = event.getEventUserUes() == status ? 0 : status;
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.updateUserEventStatus(((MainActivity) getActivity()).getSessionIDHeader(), event.getEventID(), endStatus).enqueue(new Callback<Void>() { retrofitInterface.updateUserEventStatus(((MainActivity) getActivity()).getSessionIDHeader(), event.getEventID(), endStatus).enqueue(new Callback<Void>() {
@Override @Override
public void onResponse(Call<Void> call, Response<Void> response) { public void onResponse(Call<Void> call, Response<Void> response) {
...@@ -329,7 +317,6 @@ public class EventFragment extends BackHandledFragment { ...@@ -329,7 +317,6 @@ public class EventFragment extends BackHandledFragment {
} }
event.setEventUserUes(endStatus); event.setEventUserUes(endStatus);
new updateDbEvent().execute(event);
setFollowButtonColors(endStatus); setFollowButtonColors(endStatus);
} }
} }
...@@ -479,12 +466,4 @@ public class EventFragment extends BackHandledFragment { ...@@ -479,12 +466,4 @@ public class EventFragment extends BackHandledFragment {
set.start(); set.start();
mCurrentAnimator = set; mCurrentAnimator = set;
} }
private class updateDbEvent extends AsyncTask<Event, Void, Integer> {
@Override
protected Integer doInBackground(Event... event) {
appDatabase.dbDao().updateEvent(event[0]);
return 1;
}
}
} }
...@@ -15,10 +15,10 @@ import com.google.gson.reflect.TypeToken; ...@@ -15,10 +15,10 @@ import com.google.gson.reflect.TypeToken;
import java.util.List; import java.util.List;
import app.insti.Constants; import app.insti.Constants;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.adapter.FeedAdapter; import app.insti.adapter.FeedAdapter;
import app.insti.data.Event; import app.insti.api.model.Event;
/** /**
* A simple {@link Fragment} subclass. * A simple {@link Fragment} subclass.
......
...@@ -20,18 +20,17 @@ import java.util.ArrayList; ...@@ -20,18 +20,17 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import app.insti.Constants; import app.insti.Constants;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.activity.MainActivity; import app.insti.activity.MainActivity;
import app.insti.adapter.BodyAdapter; import app.insti.adapter.BodyAdapter;
import app.insti.adapter.FeedAdapter; import app.insti.adapter.FeedAdapter;
import app.insti.adapter.UserAdapter; import app.insti.adapter.UserAdapter;
import app.insti.api.RetrofitInterface; import app.insti.api.RetrofitInterface;
import app.insti.api.ServiceGenerator; import app.insti.api.response.ExploreResponse;
import app.insti.api.model.ExploreResponse; import app.insti.api.model.Body;
import app.insti.data.Body; import app.insti.api.model.Event;
import app.insti.data.Event; import app.insti.api.model.User;
import app.insti.data.User;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
...@@ -87,7 +86,7 @@ public class ExploreFragment extends Fragment { ...@@ -87,7 +86,7 @@ public class ExploreFragment extends Fragment {
// Get all bodies // Get all bodies
if (allBodies.size() == 0) { if (allBodies.size() == 0) {
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.getAllBodies(sessionId).enqueue(new Callback<List<Body>>() { retrofitInterface.getAllBodies(sessionId).enqueue(new Callback<List<Body>>() {
@Override @Override
public void onResponse(Call<List<Body>> call, Response<List<Body>> response) { public void onResponse(Call<List<Body>> call, Response<List<Body>> response) {
...@@ -141,7 +140,7 @@ public class ExploreFragment extends Fragment { ...@@ -141,7 +140,7 @@ public class ExploreFragment extends Fragment {
getView().findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE); getView().findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);
// Make request // Make request
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.search(sessionId, query).enqueue(new Callback<ExploreResponse>() { retrofitInterface.search(sessionId, query).enqueue(new Callback<ExploreResponse>() {
@Override @Override
public void onResponse(Call<ExploreResponse> call, Response<ExploreResponse> response) { public void onResponse(Call<ExploreResponse> call, Response<ExploreResponse> response) {
......
...@@ -2,7 +2,6 @@ package app.insti.fragment; ...@@ -2,7 +2,6 @@ package app.insti.fragment;
import android.app.Activity; import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.support.design.widget.FloatingActionButton; import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
...@@ -22,15 +21,13 @@ import java.util.List; ...@@ -22,15 +21,13 @@ import java.util.List;
import app.insti.ActivityBuffer; import app.insti.ActivityBuffer;
import app.insti.Constants; import app.insti.Constants;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.activity.MainActivity; import app.insti.activity.MainActivity;
import app.insti.adapter.FeedAdapter; import app.insti.adapter.FeedAdapter;
import app.insti.api.RetrofitInterface; import app.insti.api.RetrofitInterface;
import app.insti.api.ServiceGenerator; import app.insti.api.response.NewsFeedResponse;
import app.insti.api.model.NewsFeedResponse; import app.insti.api.model.Event;
import app.insti.data.AppDatabase;
import app.insti.data.Event;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
...@@ -42,7 +39,6 @@ public class FeedFragment extends BaseFragment { ...@@ -42,7 +39,6 @@ public class FeedFragment extends BaseFragment {
private RecyclerView feedRecyclerView; private RecyclerView feedRecyclerView;
private SwipeRefreshLayout feedSwipeRefreshLayout; private SwipeRefreshLayout feedSwipeRefreshLayout;
private AppDatabase appDatabase;
private FloatingActionButton fab; private FloatingActionButton fab;
private boolean freshEventsDisplayed = false; private boolean freshEventsDisplayed = false;
LinearLayoutManager mLayoutManager; LinearLayoutManager mLayoutManager;
...@@ -78,8 +74,6 @@ public class FeedFragment extends BaseFragment { ...@@ -78,8 +74,6 @@ public class FeedFragment extends BaseFragment {
@Override @Override
public void onStart() { public void onStart() {
super.onStart(); super.onStart();
appDatabase = AppDatabase.getAppDatabase(getContext());
new showEventsFromDB().execute();
fab = (FloatingActionButton) getView().findViewById(R.id.fab); fab = (FloatingActionButton) getView().findViewById(R.id.fab);
updateFeed(); updateFeed();
} }
...@@ -104,9 +98,9 @@ public class FeedFragment extends BaseFragment { ...@@ -104,9 +98,9 @@ public class FeedFragment extends BaseFragment {
} }
} }
private void updateFeed() { private void updateFeed() {
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class);
RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.getNewsFeed("sessionid=" + getArguments().getString(Constants.SESSION_ID)).enqueue(new Callback<NewsFeedResponse>() { retrofitInterface.getNewsFeed("sessionid=" + getArguments().getString(Constants.SESSION_ID)).enqueue(new Callback<NewsFeedResponse>() {
@Override @Override
public void onResponse(Call<NewsFeedResponse> call, Response<NewsFeedResponse> response) { public void onResponse(Call<NewsFeedResponse> call, Response<NewsFeedResponse> response) {
...@@ -115,8 +109,6 @@ public class FeedFragment extends BaseFragment { ...@@ -115,8 +109,6 @@ public class FeedFragment extends BaseFragment {
List<Event> events = newsFeedResponse.getEvents(); List<Event> events = newsFeedResponse.getEvents();
freshEventsDisplayed = true; freshEventsDisplayed = true;
displayEvents(events); displayEvents(events);
new updateDatabase().execute(events);
} }
//Server Error //Server Error
feedSwipeRefreshLayout.setRefreshing(false); feedSwipeRefreshLayout.setRefreshing(false);
...@@ -192,26 +184,4 @@ public class FeedFragment extends BaseFragment { ...@@ -192,26 +184,4 @@ public class FeedFragment extends BaseFragment {
if (view != null) if (view != null)
view.setVisibility(View.GONE); view.setVisibility(View.GONE);
} }
private class updateDatabase extends AsyncTask<List<Event>, Void, Integer> {
@Override
protected Integer doInBackground(List<Event>... events) {
appDatabase.dbDao().deleteEvents();
appDatabase.dbDao().insertEvents(events[0]);
return 1;
}
}
private class showEventsFromDB extends AsyncTask<String, Void, List<Event>> {
@Override
protected List<Event> doInBackground(String... events) {
return appDatabase.dbDao().getAllEvents();
}
protected void onPostExecute(List<Event> result) {
if (!freshEventsDisplayed) {
displayEvents(result);
}
}
}
} }
...@@ -15,7 +15,6 @@ import android.location.LocationListener; ...@@ -15,7 +15,6 @@ import android.location.LocationListener;
import android.location.LocationManager; import android.location.LocationManager;
import android.media.AudioManager; import android.media.AudioManager;
import android.media.SoundPool; import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.os.Message; import android.os.Message;
...@@ -90,9 +89,7 @@ import app.insti.Constants; ...@@ -90,9 +89,7 @@ import app.insti.Constants;
import app.insti.R; import app.insti.R;
import app.insti.activity.MainActivity; import app.insti.activity.MainActivity;
import app.insti.api.RetrofitInterface; import app.insti.api.RetrofitInterface;
import app.insti.api.ServiceGenerator; import app.insti.api.model.Venue;
import app.insti.data.AppDatabase;
import app.insti.data.Venue;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
...@@ -129,7 +126,6 @@ public class MapFragment extends Fragment implements TextWatcher, ...@@ -129,7 +126,6 @@ public class MapFragment extends Fragment implements TextWatcher,
public ImageButton addMarkerIcon; public ImageButton addMarkerIcon;
public SoundPool soundPool; public SoundPool soundPool;
public int[] soundPoolIds; public int[] soundPoolIds;
private AppDatabase appDatabase;
private SettingsManager settingsManager; private SettingsManager settingsManager;
private FuzzySearchAdapter adapter; private FuzzySearchAdapter adapter;
private ExpandableListAdapter expAdapter; private ExpandableListAdapter expAdapter;
...@@ -223,21 +219,18 @@ public class MapFragment extends Fragment implements TextWatcher, ...@@ -223,21 +219,18 @@ public class MapFragment extends Fragment implements TextWatcher,
toolbar.setTitle("InstiMap"); toolbar.setTitle("InstiMap");
/* Initialize */ /* Initialize */
appDatabase = AppDatabase.getAppDatabase(getContext());
editText = (EditText) getView().findViewById(R.id.search); editText = (EditText) getView().findViewById(R.id.search);
setFonts(); setFonts();
getAPILocations(); getAPILocations();
new showLocationsFromDB().execute();
} }
private void getAPILocations() { private void getAPILocations() {
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.getAllVenues().enqueue(new Callback<List<Venue>>() { retrofitInterface.getAllVenues().enqueue(new Callback<List<Venue>>() {
@Override @Override
public void onResponse(Call<List<Venue>> call, Response<List<Venue>> response) { public void onResponse(Call<List<Venue>> call, Response<List<Venue>> response) {
if (response.isSuccessful()) { if (response.isSuccessful()) {
new updateDatabase().execute(response.body());
if (!locationsShown) { if (!locationsShown) {
setupWithData(response.body()); setupWithData(response.body());
locationsShown = true; locationsShown = true;
...@@ -1026,29 +1019,6 @@ public class MapFragment extends Fragment implements TextWatcher, ...@@ -1026,29 +1019,6 @@ public class MapFragment extends Fragment implements TextWatcher,
}); });
} }
private class updateDatabase extends AsyncTask<List<Venue>, Void, Integer> {
@Override
protected Integer doInBackground(List<Venue>... venues) {
appDatabase.dbDao().deleteVenues();
appDatabase.dbDao().insertVenues(venues[0]);
return 1;
}
}
private class showLocationsFromDB extends AsyncTask<String, Void, List<Venue>> {
@Override
protected List<Venue> doInBackground(String... events) {
return appDatabase.dbDao().getAllVenues();
}
protected void onPostExecute(List<Venue> result) {
if (!locationsShown && result.size() > 0) {
setupWithData(result);
locationsShown = true;
}
}
}
private class CustomListAdapter extends ArrayAdapter<String> { private class CustomListAdapter extends ArrayAdapter<String> {
private Context mContext; private Context mContext;
......
...@@ -2,7 +2,6 @@ package app.insti.fragment; ...@@ -2,7 +2,6 @@ package app.insti.fragment;
import android.app.Activity; import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout;
...@@ -24,12 +23,11 @@ import java.util.Locale; ...@@ -24,12 +23,11 @@ import java.util.Locale;
import app.insti.ActivityBuffer; import app.insti.ActivityBuffer;
import app.insti.Constants; import app.insti.Constants;
import app.insti.R; import app.insti.R;
import app.insti.activity.MainActivity;
import app.insti.adapter.MessMenuAdapter; import app.insti.adapter.MessMenuAdapter;
import app.insti.api.RetrofitInterface; import app.insti.api.RetrofitInterface;
import app.insti.api.ServiceGenerator; import app.insti.api.model.HostelMessMenu;
import app.insti.data.AppDatabase; import app.insti.api.model.MessMenu;
import app.insti.data.HostelMessMenu;
import app.insti.data.MessMenu;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
...@@ -41,7 +39,6 @@ public class MessMenuFragment extends BaseFragment { ...@@ -41,7 +39,6 @@ public class MessMenuFragment extends BaseFragment {
private RecyclerView messMenuRecyclerView; private RecyclerView messMenuRecyclerView;
private SwipeRefreshLayout messMenuSwipeRefreshLayout; private SwipeRefreshLayout messMenuSwipeRefreshLayout;
private AppDatabase appDatabase;
private Spinner hostelSpinner; private Spinner hostelSpinner;
private String hostel; private String hostel;
...@@ -106,14 +103,11 @@ public class MessMenuFragment extends BaseFragment { ...@@ -106,14 +103,11 @@ public class MessMenuFragment extends BaseFragment {
} }
private void displayMenu(final String hostel) { private void displayMenu(final String hostel) {
appDatabase = AppDatabase.getAppDatabase(getContext());
new showMessMenuFromDB().execute(hostel);
updateMessMenu(hostel); updateMessMenu(hostel);
} }
private void updateMessMenu(final String hostel) { private void updateMessMenu(final String hostel) {
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.getInstituteMessMenu("sessionid=" + getArguments().getString(Constants.SESSION_ID)).enqueue(new Callback<List<HostelMessMenu>>() { retrofitInterface.getInstituteMessMenu("sessionid=" + getArguments().getString(Constants.SESSION_ID)).enqueue(new Callback<List<HostelMessMenu>>() {
@Override @Override
public void onResponse(Call<List<HostelMessMenu>> call, Response<List<HostelMessMenu>> response) { public void onResponse(Call<List<HostelMessMenu>> call, Response<List<HostelMessMenu>> response) {
...@@ -122,8 +116,6 @@ public class MessMenuFragment extends BaseFragment { ...@@ -122,8 +116,6 @@ public class MessMenuFragment extends BaseFragment {
HostelMessMenu hostelMessMenu = findMessMenu(instituteMessMenu, hostel); HostelMessMenu hostelMessMenu = findMessMenu(instituteMessMenu, hostel);
if(hostelMessMenu != null) if(hostelMessMenu != null)
displayMessMenu(hostelMessMenu); displayMessMenu(hostelMessMenu);
new updateDatabase().execute(instituteMessMenu);
} }
//Server Error //Server Error
messMenuSwipeRefreshLayout.setRefreshing(false); messMenuSwipeRefreshLayout.setRefreshing(false);
...@@ -186,27 +178,4 @@ public class MessMenuFragment extends BaseFragment { ...@@ -186,27 +178,4 @@ public class MessMenuFragment extends BaseFragment {
}); });
getActivity().findViewById(R.id.loadingPanel).setVisibility(View.GONE); getActivity().findViewById(R.id.loadingPanel).setVisibility(View.GONE);
} }
private class updateDatabase extends AsyncTask<List<HostelMessMenu>, Void, Integer> {
@Override
protected Integer doInBackground(List<HostelMessMenu>... menus) {
appDatabase.dbDao().deleteHostelMessMenus();
appDatabase.dbDao().insertHostelMessMenus(menus[0]);
return 1;
}
}
public class showMessMenuFromDB extends AsyncTask<String, Void, HostelMessMenu> {
@Override
protected HostelMessMenu doInBackground(String... strings) {
return findMessMenu(appDatabase.dbDao().getAllHostelMessMenus(), strings[0]);
}
@Override
protected void onPostExecute(HostelMessMenu hostelMessMenu) {
if (hostelMessMenu != null)
displayMessMenu(hostelMessMenu);
}
}
} }
package app.insti.fragment;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.gson.Gson;
import java.util.List;
import app.insti.ActivityBuffer;
import app.insti.Constants;
import app.insti.ItemClickListener;
import app.insti.R;
import app.insti.activity.MainActivity;
import app.insti.adapter.FeedAdapter;
import app.insti.data.AppDatabase;
import app.insti.data.Event;
/**
* A simple {@link Fragment} subclass.
*/
public class MyEventsFragment extends BaseFragment {
private RecyclerView myEventsFeedRecyclerView;
private SwipeRefreshLayout myEventsFeedSwipeRefreshLayout;
private AppDatabase appDatabase;
private FloatingActionButton fab;
public MyEventsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_events, container, false);
Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setTitle("My Events");
fab = (FloatingActionButton) view.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AddEventFragment addEventFragment = new AddEventFragment();
((MainActivity) getActivity()).updateFragment(addEventFragment);
}
});
return view;
}
@Override
public void onStart() {
super.onStart();
if (((MainActivity) getActivity()).createEventAccess()) {
fab.setVisibility(View.VISIBLE);
}
appDatabase = AppDatabase.getAppDatabase(getContext());
new showEvents().execute();
myEventsFeedSwipeRefreshLayout = getActivity().findViewById(R.id.my_events_feed_swipe_refresh_layout);
myEventsFeedSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
updateOnRefresh();
myEventsFeedSwipeRefreshLayout.setRefreshing(false);
}
});
}
private void updateOnRefresh() {
new showEvents().execute();
}
private void displayEvents(final List<Event> events) {
/* Check if already destroyed */
if (getActivity() == null || getView() == null) return;
final FeedAdapter feedAdapter = new FeedAdapter(events, new ItemClickListener() {
@Override
public void onItemClick(View v, int position) {
String eventJson = new Gson().toJson(events.get(position));
Bundle bundle = getArguments();
if (bundle == null)
bundle = new Bundle();
bundle.putString(Constants.EVENT_JSON, eventJson);
EventFragment eventFragment = new EventFragment();
eventFragment.setArguments(bundle);
FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left, R.anim.slide_in_right, R.anim.slide_out_right);
transaction.replace(R.id.framelayout_for_fragment, eventFragment, eventFragment.getTag());
transaction.addToBackStack(eventFragment.getTag()).commit();
}
});
getActivityBuffer().safely(new ActivityBuffer.IRunnable() {
@Override
public void run(Activity pActivity) {
try {
myEventsFeedRecyclerView = getActivity().findViewById(R.id.my_events_feed_recycler_view);
myEventsFeedRecyclerView.setAdapter(feedAdapter);
myEventsFeedRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
getActivity().findViewById(R.id.loadingPanel).setVisibility(View.GONE);
}
private class showEvents extends AsyncTask<String, Void, List<Event>> {
@Override
protected List<Event> doInBackground(String... events) {
return appDatabase.dbDao().getFollowingEvents();
}
protected void onPostExecute(List<Event> result) {
displayEvents(result);
}
}
}
\ No newline at end of file
package app.insti.fragment; package app.insti.fragment;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar; import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import app.insti.ActivityBuffer;
import app.insti.Constants;
import app.insti.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.activity.MainActivity; import app.insti.activity.MainActivity;
import app.insti.adapter.NewsAdapter; import app.insti.adapter.NewsAdapter;
import app.insti.api.RetrofitInterface; import app.insti.api.RetrofitInterface;
import app.insti.api.ServiceGenerator; import app.insti.api.model.NewsArticle;
import app.insti.data.AppDatabase;
import app.insti.data.NewsArticle;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/** /**
* A simple {@link Fragment} subclass. * A simple {@link Fragment} subclass.
*/ */
public class NewsFragment extends BaseFragment { public class NewsFragment extends RecyclerViewFragment<NewsArticle, NewsAdapter> {
public static boolean showLoader = true;
private RecyclerView newsRecyclerView;
private SwipeRefreshLayout newsSwipeRefreshLayout;
private AppDatabase appDatabase;
private boolean freshNewsDisplayed = false;
private String searchQuery;
public NewsFragment() { public NewsFragment() {
// Required empty public constructor // Required empty public constructor
...@@ -67,172 +40,23 @@ public class NewsFragment extends BaseFragment { ...@@ -67,172 +40,23 @@ public class NewsFragment extends BaseFragment {
Toolbar toolbar = getActivity().findViewById(R.id.toolbar); Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setTitle("News"); toolbar.setTitle("News");
setHasOptionsMenu(true); setHasOptionsMenu(true);
updateData();
appDatabase = AppDatabase.getAppDatabase(getContext()); postType = NewsArticle.class;
new NewsFragment.showNewsFromDB().execute(); adapterType = NewsAdapter.class;
recyclerView = getActivity().findViewById(R.id.news_recycler_view);
updateNews(); swipeRefreshLayout = getActivity().findViewById(R.id.news_swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
newsSwipeRefreshLayout = getActivity().findViewById(R.id.news_swipe_refresh_layout);
newsSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override @Override
public void onRefresh() { public void onRefresh() {
updateNews(); updateData();
}
});
}
private void updateNews() {
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class);
retrofitInterface.getNews("sessionid=" + getArguments().getString(Constants.SESSION_ID), 0, 20, searchQuery).enqueue(new Callback<List<NewsArticle>>() {
@Override
public void onResponse(Call<List<NewsArticle>> call, Response<List<NewsArticle>> response) {
if (response.isSuccessful()) {
List<NewsArticle> articles = response.body();
freshNewsDisplayed = true;
displayNews(articles);
new updateDatabase().execute(articles);
}
//Server Error
newsSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void onFailure(Call<List<NewsArticle>> call, Throwable t) {
//Network Error
newsSwipeRefreshLayout.setRefreshing(false);
} }
}); });
} }
private void displayNews(final List<NewsArticle> result) {
/* Skip if we're already destroyed */
if (getActivity() == null || getView() == null) return;
final NewsAdapter newsAdapter = new NewsAdapter(result, new ItemClickListener() {
@Override
public void onItemClick(View v, int position) {
String link = result.get(position).getLink();
if (link != null && !link.isEmpty())
openWebURL(link);
}
});
getActivityBuffer().safely(new ActivityBuffer.IRunnable() {
@Override
public void run(Activity pActivity) {
try {
newsRecyclerView = getActivity().findViewById(R.id.news_recycler_view);
newsRecyclerView.setAdapter(newsAdapter);
newsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
newsRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
// multiple calls should not be made
boolean loading = false;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy > 0) {
LinearLayoutManager layoutManager = (LinearLayoutManager) newsRecyclerView.getLayoutManager();
if (((layoutManager.getChildCount() + layoutManager.findFirstVisibleItemPosition()) > (layoutManager.getItemCount() - 5)) && (!loading)) {
loading = true;
View v = getActivity().findViewById(R.id.training_feed_swipe_refresh_layout);
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class);
retrofitInterface.getNews("sessionid=" + getArguments().getString(Constants.SESSION_ID), layoutManager.getItemCount(), 10, searchQuery).enqueue(new Callback<List<NewsArticle>>() {
@Override
public void onResponse(Call<List<NewsArticle>> call, Response<List<NewsArticle>> response) {
loading = false;
List<NewsArticle> newsArticles = (ArrayList<NewsArticle>) newsAdapter.getNewsArticles();
newsArticles.addAll(response.body());
if (response.body().size() == 0) {
showLoader = false;
}
newsAdapter.setNewsArticles(newsArticles);
newsAdapter.notifyDataSetChanged();
// new updateDatabase().execute(blogPosts);
}
@Override
public void onFailure(Call<List<NewsArticle>> call, Throwable t) {
loading = false;
}
});
}
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
getActivity().findViewById(R.id.loadingPanel).setVisibility(View.GONE);
}
private void openWebURL(String URL) {
Intent browse = new Intent(Intent.ACTION_VIEW, Uri.parse(URL));
startActivity(browse);
}
@Override @Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { Call<List<NewsArticle>> getCall(RetrofitInterface retrofitInterface, String sessionIDHeader) {
inflater.inflate(R.menu.search_view_menu, menu); return retrofitInterface.getNews(sessionIDHeader, getPostCount(), 20, searchQuery);
MenuItem item = menu.findItem(R.id.action_search);
SearchView sv = new SearchView(((MainActivity) getActivity()).getSupportActionBar().getThemedContext());
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItem.SHOW_AS_ACTION_IF_ROOM);
item.setActionView(sv);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
performSearch(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
//Text is cleared, do your thing
searchQuery = null;
updateNews();
showLoader = true;
return true;
} else if (newText.length() >= 3) {
performSearch(newText);
return true;
}
return false;
}
});
}
private void performSearch(String query) {
searchQuery = query;
updateNews();
showLoader = false;
}
private class updateDatabase extends AsyncTask<List<NewsArticle>, Void, Integer> {
@Override
protected Integer doInBackground(List<NewsArticle>... posts) {
appDatabase.dbDao().deleteNewsArticles();
appDatabase.dbDao().insertNewsArticles(posts[0]);
return 1;
}
}
private class showNewsFromDB extends AsyncTask<String, Void, List<NewsArticle>> {
@Override
protected List<NewsArticle> doInBackground(String... posts) {
return appDatabase.dbDao().getAllNewsArticles();
}
protected void onPostExecute(List<NewsArticle> result) {
if (!freshNewsDisplayed) {
displayNews(result);
}
}
} }
} }
...@@ -17,14 +17,14 @@ import com.google.gson.Gson; ...@@ -17,14 +17,14 @@ import com.google.gson.Gson;
import java.util.List; import java.util.List;
import app.insti.Constants; import app.insti.Constants;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.activity.MainActivity; import app.insti.activity.MainActivity;
import app.insti.adapter.NotificationsAdapter; import app.insti.adapter.NotificationsAdapter;
import app.insti.api.EmptyCallback;
import app.insti.api.RetrofitInterface; import app.insti.api.RetrofitInterface;
import app.insti.api.ServiceGenerator; import app.insti.api.model.Notification;
import app.insti.data.Notification; import app.insti.api.model.PlacementBlogPost;
import app.insti.data.PlacementBlogPost;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
...@@ -57,7 +57,7 @@ public class NotificationsFragment extends BaseFragment { ...@@ -57,7 +57,7 @@ public class NotificationsFragment extends BaseFragment {
Toolbar toolbar = getActivity().findViewById(R.id.toolbar); Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setTitle("Notifications"); toolbar.setTitle("Notifications");
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.getNotifications(((MainActivity) getActivity()).getSessionIDHeader()).enqueue(new Callback<List<Notification>>() { retrofitInterface.getNotifications(((MainActivity) getActivity()).getSessionIDHeader()).enqueue(new Callback<List<Notification>>() {
@Override @Override
public void onResponse(Call<List<Notification>> call, Response<List<Notification>> response) { public void onResponse(Call<List<Notification>> call, Response<List<Notification>> response) {
...@@ -87,17 +87,9 @@ public class NotificationsFragment extends BaseFragment { ...@@ -87,17 +87,9 @@ public class NotificationsFragment extends BaseFragment {
Notification notification = notifications.get(position); Notification notification = notifications.get(position);
/* Mark notification read */ /* Mark notification read */
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
String sessId = ((MainActivity) getActivity()).getSessionIDHeader(); String sessId = ((MainActivity) getActivity()).getSessionIDHeader();
retrofitInterface.markNotificationRead(sessId, notification.getNotificationId()).enqueue(new Callback<Void>() { retrofitInterface.markNotificationRead(sessId, notification.getNotificationId().toString()).enqueue(new EmptyCallback<Void>());
@Override
public void onResponse(Call<Void> call, Response<Void> response) {
}
@Override
public void onFailure(Call<Void> call, Throwable t) {
}
});
FragmentManager manager = getActivity().getSupportFragmentManager(); FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction(); FragmentTransaction transaction = manager.beginTransaction();
......
package app.insti.fragment;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import app.insti.ActivityBuffer;
import app.insti.api.RetrofitInterface;
import app.insti.interfaces.Browsable;
import app.insti.interfaces.ItemClickListener;
import app.insti.R;
import app.insti.interfaces.Readable;
import app.insti.interfaces.Writable;
import app.insti.activity.MainActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.view.View.GONE;
public abstract class RecyclerViewFragment<T extends Browsable, S extends RecyclerView.Adapter<RecyclerView.ViewHolder> & Readable<T> & Writable<T>> extends BaseFragment {
public static boolean showLoader = true;
protected RecyclerView recyclerView;
protected Class<T> postType;
protected Class<S> adapterType;
protected SwipeRefreshLayout swipeRefreshLayout;
protected String searchQuery;
private S adapter = null;
protected void updateData() {
String sessionIDHeader = ((MainActivity) getActivity()).getSessionIDHeader();
RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
Call<List<T>> call = getCall(retrofitInterface, sessionIDHeader);
call.enqueue(new Callback<List<T>>() {
@Override
public void onResponse(Call<List<T>> call, Response<List<T>> response) {
if (response.isSuccessful()) {
List<T> posts = response.body();
displayData(posts);
}
swipeRefreshLayout.setRefreshing(false);
}
@Override
public void onFailure(Call<List<T>> call, Throwable t) {
swipeRefreshLayout.setRefreshing(false);
}
});
}
abstract Call<List<T>> getCall(RetrofitInterface retrofitInterface, String sessionIDHeader);
private void displayData(final List<T> result) {
/* Skip if we're already destroyed */
if (getActivity() == null || getView() == null) return;
try {
adapter = adapterType.getDeclaredConstructor(List.class, ItemClickListener.class).newInstance(result, new ItemClickListener() {
@Override
public void onItemClick(View v, int position) {
String link = result.get(position).getLink();
if (link != null && !link.isEmpty())
openWebURL(link);
}
});
getActivityBuffer().safely(new ActivityBuffer.IRunnable() {
@Override
public void run(Activity pActivity) {
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
boolean loading = false;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy > 0) {
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (((layoutManager.getChildCount() + layoutManager.findFirstVisibleItemPosition()) > (layoutManager.getItemCount() - 5)) && (!loading)) {
loading = true;
String sessionIDHeader = ((MainActivity) getActivity()).getSessionIDHeader();
RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
Call<List<T>> call = getCall(retrofitInterface, sessionIDHeader);
call.enqueue(new Callback<List<T>>() {
@Override
public void onResponse(Call<List<T>> call, Response<List<T>> response) {
if (response.isSuccessful()) {
loading = false;
List<T> posts = adapter.getPosts();
posts.addAll(response.body());
if (response.body().size() == 0) {
showLoader = false;
}
adapter.setPosts(posts);
adapter.notifyDataSetChanged();
}
}
@Override
public void onFailure(Call<List<T>> call, Throwable t) {
loading = false;
}
});
}
}
}
});
}
});
getActivity().findViewById(R.id.loadingPanel).setVisibility(GONE);
} catch (java.lang.InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
}
protected int getPostCount() {
if (adapter == null) { return 0; }
return adapter.getPosts().size();
}
private void openWebURL(String URL) {
Intent browse = new Intent(Intent.ACTION_VIEW, Uri.parse(URL));
startActivity(browse);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search_view_menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView sv = new SearchView(((MainActivity) getActivity()).getSupportActionBar().getThemedContext());
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItem.SHOW_AS_ACTION_IF_ROOM);
item.setActionView(sv);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
performSearch(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
searchQuery = null;
updateData();
showLoader = true;
return true;
} else if (newText.length() >= 3) {
performSearch(newText);
return true;
}
return false;
}
});
}
private void performSearch(String query) {
searchQuery = query;
updateData();
showLoader = false;
}
}
...@@ -23,8 +23,7 @@ import app.insti.SessionManager; ...@@ -23,8 +23,7 @@ import app.insti.SessionManager;
import app.insti.activity.LoginActivity; import app.insti.activity.LoginActivity;
import app.insti.activity.MainActivity; import app.insti.activity.MainActivity;
import app.insti.api.RetrofitInterface; import app.insti.api.RetrofitInterface;
import app.insti.api.ServiceGenerator; import app.insti.api.model.User;
import app.insti.data.User;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
...@@ -58,7 +57,7 @@ public class SettingsFragment extends Fragment { ...@@ -58,7 +57,7 @@ public class SettingsFragment extends Fragment {
populateViews(); populateViews();
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.getUser("sessionid=" + getArguments().getString(Constants.SESSION_ID), userID).enqueue(new Callback<User>() { retrofitInterface.getUser("sessionid=" + getArguments().getString(Constants.SESSION_ID), userID).enqueue(new Callback<User>() {
@Override @Override
public void onResponse(Call<User> call, Response<User> response) { public void onResponse(Call<User> call, Response<User> response) {
...@@ -139,7 +138,7 @@ public class SettingsFragment extends Fragment { ...@@ -139,7 +138,7 @@ public class SettingsFragment extends Fragment {
logoutButton.setOnClickListener(new View.OnClickListener() { logoutButton.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.logout("sessionid=" + getArguments().getString(Constants.SESSION_ID)).enqueue(new Callback<Void>() { retrofitInterface.logout("sessionid=" + getArguments().getString(Constants.SESSION_ID)).enqueue(new Callback<Void>() {
@Override @Override
public void onResponse(Call<Void> call, Response<Void> response) { public void onResponse(Call<Void> call, Response<Void> response) {
......
...@@ -4,7 +4,6 @@ package app.insti.fragment; ...@@ -4,7 +4,6 @@ package app.insti.fragment;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.net.Uri; import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.support.v4.app.Fragment; import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout;
...@@ -25,14 +24,12 @@ import java.util.List; ...@@ -25,14 +24,12 @@ import java.util.List;
import app.insti.ActivityBuffer; import app.insti.ActivityBuffer;
import app.insti.Constants; import app.insti.Constants;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.activity.MainActivity; import app.insti.activity.MainActivity;
import app.insti.adapter.TrainingBlogAdapter; import app.insti.adapter.TrainingBlogAdapter;
import app.insti.api.RetrofitInterface; import app.insti.api.RetrofitInterface;
import app.insti.api.ServiceGenerator; import app.insti.api.model.TrainingBlogPost;
import app.insti.data.AppDatabase;
import app.insti.data.TrainingBlogPost;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
...@@ -40,15 +37,7 @@ import retrofit2.Response; ...@@ -40,15 +37,7 @@ import retrofit2.Response;
/** /**
* A simple {@link Fragment} subclass. * A simple {@link Fragment} subclass.
*/ */
public class TrainingBlogFragment extends BaseFragment { public class TrainingBlogFragment extends RecyclerViewFragment<TrainingBlogPost, TrainingBlogAdapter> {
public static boolean showLoader = true;
private RecyclerView trainingFeedRecyclerView;
private SwipeRefreshLayout feedSwipeRefreshLayout;
private AppDatabase appDatabase;
private boolean freshBlogDisplayed = false;
private String searchQuery;
public TrainingBlogFragment() { public TrainingBlogFragment() {
// Required empty public constructor // Required empty public constructor
...@@ -68,170 +57,23 @@ public class TrainingBlogFragment extends BaseFragment { ...@@ -68,170 +57,23 @@ public class TrainingBlogFragment extends BaseFragment {
Toolbar toolbar = getActivity().findViewById(R.id.toolbar); Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setTitle("Internship Blog"); toolbar.setTitle("Internship Blog");
setHasOptionsMenu(true); setHasOptionsMenu(true);
updateData();
appDatabase = AppDatabase.getAppDatabase(getContext()); postType = TrainingBlogPost.class;
new TrainingBlogFragment.showTrainingBlogFromDB().execute(); adapterType = TrainingBlogAdapter.class;
recyclerView = getActivity().findViewById(R.id.training_feed_recycler_view);
updateTrainingFeed(); swipeRefreshLayout = getActivity().findViewById(R.id.training_feed_swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
feedSwipeRefreshLayout = getActivity().findViewById(R.id.training_feed_swipe_refresh_layout);
feedSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override @Override
public void onRefresh() { public void onRefresh() {
updateTrainingFeed(); updateData();
}
});
}
private void updateTrainingFeed() {
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class);
retrofitInterface.getTrainingBlogFeed("sessionid=" + getArguments().getString(Constants.SESSION_ID), 0, 20, searchQuery).enqueue(new Callback<List<TrainingBlogPost>>() {
@Override
public void onResponse(Call<List<TrainingBlogPost>> call, Response<List<TrainingBlogPost>> response) {
if (response.isSuccessful()) {
List<TrainingBlogPost> posts = response.body();
freshBlogDisplayed = true;
displayTrainingFeed(posts);
new updateDatabase().execute(posts);
}
//Server Error
feedSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void onFailure(Call<List<TrainingBlogPost>> call, Throwable t) {
//Network Error
feedSwipeRefreshLayout.setRefreshing(false);
} }
}); });
} }
private void displayTrainingFeed(final List<TrainingBlogPost> result) {
/* Skip if we're already destroyed */
if (getActivity() == null || getView() == null) return;
final TrainingBlogAdapter trainingBlogAdapter = new TrainingBlogAdapter(result, new ItemClickListener() {
@Override
public void onItemClick(View v, int position) {
openWebURL(result.get(position).getLink());
}
});
getActivityBuffer().safely(new ActivityBuffer.IRunnable() {
@Override
public void run(Activity pActivity) {
try {
trainingFeedRecyclerView = getActivity().findViewById(R.id.training_feed_recycler_view);
trainingFeedRecyclerView.setAdapter(trainingBlogAdapter);
trainingFeedRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
trainingFeedRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
// multiple calls should not be made
boolean loading = false;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy > 0) {
LinearLayoutManager layoutManager = (LinearLayoutManager) trainingFeedRecyclerView.getLayoutManager();
if (((layoutManager.getChildCount() + layoutManager.findFirstVisibleItemPosition()) > (layoutManager.getItemCount() - 5)) && (!loading)) {
loading = true;
View v = getActivity().findViewById(R.id.training_feed_swipe_refresh_layout);
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class);
retrofitInterface.getTrainingBlogFeed("sessionid=" + getArguments().getString(Constants.SESSION_ID), layoutManager.getItemCount(), 10, searchQuery).enqueue(new Callback<List<TrainingBlogPost>>() {
@Override
public void onResponse(Call<List<TrainingBlogPost>> call, Response<List<TrainingBlogPost>> response) {
loading = false;
List<TrainingBlogPost> blogPosts = (ArrayList<TrainingBlogPost>) trainingBlogAdapter.getPosts();
blogPosts.addAll(response.body());
if (response.body().size() == 0) {
showLoader = false;
}
trainingBlogAdapter.setPosts(blogPosts);
trainingBlogAdapter.notifyDataSetChanged();
// new updateDatabase().execute(blogPosts);
}
@Override
public void onFailure(Call<List<TrainingBlogPost>> call, Throwable t) {
loading = false;
}
});
}
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
getActivity().findViewById(R.id.loadingPanel).setVisibility(View.GONE);
}
private void openWebURL(String URL) {
Intent browse = new Intent(Intent.ACTION_VIEW, Uri.parse(URL));
startActivity(browse);
}
@Override @Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { Call<List<TrainingBlogPost>> getCall(RetrofitInterface retrofitInterface, String sessionIDHeader) {
inflater.inflate(R.menu.search_view_menu, menu); return retrofitInterface.getTrainingBlogFeed(sessionIDHeader, getPostCount(), 20, searchQuery);
MenuItem item = menu.findItem(R.id.action_search);
SearchView sv = new SearchView(((MainActivity) getActivity()).getSupportActionBar().getThemedContext());
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW | MenuItem.SHOW_AS_ACTION_IF_ROOM);
item.setActionView(sv);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
performSearch(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
//Text is cleared, do your thing
searchQuery = null;
updateTrainingFeed();
showLoader = true;
return true;
} else if (newText.length() >= 3) {
performSearch(newText);
return true;
}
return false;
}
});
}
private void performSearch(String query) {
searchQuery = query;
updateTrainingFeed();
showLoader = false;
}
private class updateDatabase extends AsyncTask<List<TrainingBlogPost>, Void, Integer> {
@Override
protected Integer doInBackground(List<TrainingBlogPost>... posts) {
appDatabase.dbDao().deleteTrainingBlogPosts();
appDatabase.dbDao().insertTrainingBlogPosts(posts[0]);
return 1;
}
}
private class showTrainingBlogFromDB extends AsyncTask<String, Void, List<TrainingBlogPost>> {
@Override
protected List<TrainingBlogPost> doInBackground(String... posts) {
return appDatabase.dbDao().getAllTrainingBlogPosts();
}
protected void onPostExecute(List<TrainingBlogPost> result) {
if (!freshBlogDisplayed) {
displayTrainingFeed(result);
}
}
} }
} }
...@@ -31,17 +31,17 @@ import com.squareup.picasso.Picasso; ...@@ -31,17 +31,17 @@ import com.squareup.picasso.Picasso;
import java.util.List; import java.util.List;
import app.insti.Constants; import app.insti.Constants;
import app.insti.ItemClickListener; import app.insti.interfaces.ItemClickListener;
import app.insti.R; import app.insti.R;
import app.insti.ShareURLMaker; import app.insti.ShareURLMaker;
import app.insti.activity.MainActivity;
import app.insti.adapter.RoleAdapter; import app.insti.adapter.RoleAdapter;
import app.insti.adapter.TabAdapter; import app.insti.adapter.TabAdapter;
import app.insti.api.RetrofitInterface; import app.insti.api.RetrofitInterface;
import app.insti.api.ServiceGenerator; import app.insti.api.model.Body;
import app.insti.data.Body; import app.insti.api.model.Event;
import app.insti.data.Event; import app.insti.api.model.Role;
import app.insti.data.Role; import app.insti.api.model.User;
import app.insti.data.User;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
...@@ -107,7 +107,7 @@ public class UserFragment extends BackHandledFragment { ...@@ -107,7 +107,7 @@ public class UserFragment extends BackHandledFragment {
Bundle bundle = getArguments(); Bundle bundle = getArguments();
String userID = bundle.getString(Constants.USER_ID); String userID = bundle.getString(Constants.USER_ID);
RetrofitInterface retrofitInterface = ServiceGenerator.createService(RetrofitInterface.class); RetrofitInterface retrofitInterface = ((MainActivity) getActivity()).getRetrofitInterface();
retrofitInterface.getUser("sessionid=" + getArguments().getString(Constants.SESSION_ID), userID).enqueue(new Callback<User>() { retrofitInterface.getUser("sessionid=" + getArguments().getString(Constants.SESSION_ID), userID).enqueue(new Callback<User>() {
@Override @Override
public void onResponse(Call<User> call, Response<User> response) { public void onResponse(Call<User> call, Response<User> response) {
......
package app.insti.interfaces;
public interface Browsable {
String getLink();
}
package app.insti; package app.insti.interfaces;
import android.view.View; import android.view.View;
......
package app.insti.interfaces;
import java.util.List;
public interface Readable<T> {
List<T> getPosts();
}
package app.insti.interfaces;
import java.util.List;
public interface Writable<T> {
void setPosts(List<T> posts);
}
package app.insti.notifications;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import java.util.Calendar;
import java.util.Date;
public class
NotificationEventReceiver extends BroadcastReceiver {
private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
public static void setupAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = getStartPendingIntent(context);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
getTriggerAt(new Date()),
1000 * 60 * 10, //Change this to 1000 * 60 for testing => runs every minute
alarmIntent);
}
private static long getTriggerAt(Date now) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
//calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
return calendar.getTimeInMillis();
}
private static PendingIntent getStartPendingIntent(Context context) {
Intent intent = new Intent(context, NotificationEventReceiver.class);
intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static PendingIntent getDeleteIntent(Context context) {
Intent intent = new Intent(context, NotificationEventReceiver.class);
intent.setAction(ACTION_DELETE_NOTIFICATION);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Intent serviceIntent = null;
if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
} else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
}
if (serviceIntent != null) {
NotificationIntentService.enqueueWork(context, NotificationIntentService.class, 200, serviceIntent);
}
}
}
\ No newline at end of file
package app.insti.notifications;
import java.util.concurrent.atomic.AtomicInteger;
public class NotificationId {
private final static AtomicInteger c = new AtomicInteger(0);
public static int getID() {
return c.incrementAndGet();
}
}
package app.insti.notifications;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationEventReceiver.setupAlarm(context);
}
}
\ No newline at end of file
...@@ -4,7 +4,7 @@ import java.util.ArrayList; ...@@ -4,7 +4,7 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import app.insti.data.Venue; import app.insti.api.model.Venue;
public class Locations { public class Locations {
public HashMap<String, Marker> data = new HashMap<String, Marker>(); public HashMap<String, Marker> data = new HashMap<String, Marker>();
......
...@@ -10,5 +10,6 @@ ...@@ -10,5 +10,6 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" android:layout_gravity="center_horizontal"
android:layout_margin="@dimen/activity_vertical_margin" android:layout_margin="@dimen/activity_vertical_margin"
android:indeterminate="true" /> android:indeterminate="true"
android:theme="@style/BlueAccent" />
</LinearLayout> </LinearLayout>
\ No newline at end of file
...@@ -40,7 +40,8 @@ ...@@ -40,7 +40,8 @@
<android.support.v7.widget.CardView <android.support.v7.widget.CardView
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
app:cardBackgroundColor="@color/colorPrimary"> app:cardBackgroundColor="@color/colorPrimary"
app:cardCornerRadius="0dp">
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
......
...@@ -36,7 +36,8 @@ ...@@ -36,7 +36,8 @@
<android.support.v7.widget.CardView <android.support.v7.widget.CardView
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
app:cardBackgroundColor="@color/colorPrimary"> app:cardBackgroundColor="@color/colorPrimary"
app:cardCornerRadius="0dp">
<LinearLayout <LinearLayout
android:layout_width="match_parent" android:layout_width="match_parent"
......
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/my_events_feed_swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="app.insti.fragment.MyEventsFragment">
<android.support.v7.widget.RecyclerView
android:id="@+id/my_events_feed_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="8dp" />
</android.support.v4.widget.SwipeRefreshLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"
android:src="@drawable/ic_add_black_24dp"
android:tint="@android:color/black"
android:visibility="gone" />
<RelativeLayout
android:id="@+id/loadingPanel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"
android:theme="@style/BlueAccent" />
</RelativeLayout>
</RelativeLayout>
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
xmlns:tools="http://schemas.android.com/tools" xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view"> tools:showIn="navigation_view">
<!--TODO Update icons-->
<group android:checkableBehavior="single"> <group android:checkableBehavior="single">
<item <item
android:id="@+id/nav_feed" android:id="@+id/nav_feed"
...@@ -14,11 +13,6 @@ ...@@ -14,11 +13,6 @@
android:icon="@drawable/baseline_rss_feed_black_48" android:icon="@drawable/baseline_rss_feed_black_48"
android:title="News" /> android:title="News" />
<item
android:id="@+id/nav_my_events"
android:icon="@drawable/ic_event"
android:title="My Events" />
<item <item
android:id="@+id/nav_explore" android:id="@+id/nav_explore"
android:icon="@drawable/ic_search_black_24dp" android:icon="@drawable/ic_search_black_24dp"
......
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