Migrate database to Room

This commit is contained in:
Amab 2022-05-23 17:11:47 +02:00
parent 6a64bfa9fd
commit b839a3210a
175 changed files with 5756 additions and 10942 deletions

View File

@ -7,30 +7,70 @@ on:
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout Git repository - name: Checkout Git repository
uses: actions/checkout@v2 uses: actions/checkout@v3
with: with:
fetch-depth: 0 fetch-depth: 0
- name: Fetch Git tags - name: Fetch Git tags
run: git fetch --tags run: git fetch --tags
- name: set up JDK 11 - name: set up JDK 11
uses: actions/setup-java@v1 uses: actions/setup-java@v3
with: with:
java-version: 11 distribution: 'zulu' # See 'Supported distributions' for available options
- name: Cache local Gradle repository java-version: '11'
uses: actions/cache@v2 - name: Gradle cache
with: uses: gradle/gradle-build-action@v2
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Grant execute permission for gradlew - name: Grant execute permission for gradlew
run: chmod +x gradlew run: chmod +x gradlew
- name: Build with Gradle - name: Build with Gradle
run: ./gradlew build run: ./gradlew build
test:
runs-on: ubuntu-latest
strategy:
matrix:
api-level: [24, 30, 32]
target: [default, google_apis]
steps:
- name: checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Fetch Git tags
run: git fetch --tags
- name: set up JDK 11
uses: actions/setup-java@v3
with:
distribution: 'zulu' # See 'Supported distributions' for available options
java-version: '11'
- name: Gradle cache
uses: gradle/gradle-build-action@v2
- name: AVD cache
uses: actions/cache@v3
id: avd-cache
with:
path: |
~/.android/avd/*
~/.android/adb*
key: avd-${{ matrix.api-level }}
- name: create AVD and generate snapshot for caching
if: steps.avd-cache.outputs.cache-hit != 'true'
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: ${{ matrix.api-level }}
force-avd-creation: false
emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none
disable-animations: false
script: echo "Generated AVD snapshot for caching."
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: run tests
uses: reactivecircus/android-emulator-runner@v2
with:
api-level: ${{ matrix.api-level }}
force-avd-creation: false
emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none
disable-animations: true
script: ./gradlew connectedCheck

View File

@ -1,79 +0,0 @@
name: Android CI for releases
on:
push:
# Pattern matched against refs/tags
tags:
- '*' # Push events to every tag
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout Git repository
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Fetch Git tags
run: git fetch --tags
- name: set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Cache local Gradle repository
uses: actions/cache@v2
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Grant execute permission for gradlew
run: chmod +x gradlew
- name: Build with Gradle
run: ./gradlew build -Pbuild=prod
- name: Sign artifact
id: signArtifact
uses: r0adkll/sign-android-release@v1
with:
releaseDirectory: app/build/outputs/apk/release/release
alias: ${{ secrets.ALIAS }}
signingKeyBase64: ${{ secrets.KEYSTORE }}
keyStorePassword: ${{ secrets.KEYSTORE_PASSWORD }}
keyPassword: ${{ secrets.KEY_PASSWORD }}
- name: Upload artifact
uses: actions/upload-artifact@v2
with:
name: Release artifact
path: app/build/outputs/apk/release/release/SWADroid-*.apk
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
draft: false
prerelease: false
- name: Save name of Artifact
id: set-result-artifact
run: |
ARTIFACT_PATHNAME_APK=$(ls app/build/outputs/apk/release/release/*.apk | head -n 1)
ARTIFACT_NAME_APK=$(basename $ARTIFACT_PATHNAME_APK)
echo "ARTIFACT_NAME_APK is " ${ARTIFACT_NAME_APK}
echo "ARTIFACT_PATHNAME_APK=${ARTIFACT_PATHNAME_APK}" >> $GITHUB_ENV
echo "ARTIFACT_NAME_APK=${ARTIFACT_NAME_APK}" >> $GITHUB_ENV
- name: Upload Artifact Assets
id: upload-release-asset
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ${{ env.ARTIFACT_PATHNAME_APK }}
asset_name: ${{ env.ARTIFACT_NAME_APK }}
asset_content_type: application/zip

1
.gitignore vendored
View File

@ -57,3 +57,4 @@ lint/tmp/
# lint/reports/ # lint/reports/
/SWADroid/src/debug/ /SWADroid/src/debug/
/SWADroid/release/ /SWADroid/release/
/SWADroid/schemas/

View File

@ -39,30 +39,32 @@ if (build_param != "prod") {
} }
android { android {
compileSdkVersion 31 compileSdkVersion 32
buildToolsVersion "31.0.0" buildToolsVersion "32.0.0"
compileOptions { compileOptions {
sourceCompatibility JavaVersion.VERSION_11 sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11 targetCompatibility JavaVersion.VERSION_11
} }
lintOptions {
abortOnError false
}
defaultConfig { defaultConfig {
applicationId "es.ugr.swad.swadroid" applicationId "es.ugr.swad.swadroid"
versionName androidGitVersion.name() versionName androidGitVersion.name()
versionCode androidGitVersion.code() versionCode androidGitVersion.code()
minSdkVersion 24 minSdkVersion 24
targetSdkVersion 31 targetSdkVersion 32
testApplicationId "es.ugr.swad.swadroid.test" testApplicationId "es.ugr.swad.swadroid.androidTest"
testInstrumentationRunner "android.test.InstrumentationTestRunner" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
buildConfigField "String", "SWAD_APP_KEY", getBuildConfigField("SWAD_APP_KEY") buildConfigField "String", "SWAD_APP_KEY", getBuildConfigField("SWAD_APP_KEY")
javaCompileOptions {
annotationProcessorOptions {
arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
} }
buildTypes { buildTypes {
@ -72,6 +74,16 @@ android {
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
} }
} }
sourceSets {
// Adds exported schema location as androidTest app assets.
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
}
lint {
abortOnError false
}
namespace 'es.ugr.swad.swadroid'
} }
dependencies { dependencies {
@ -86,4 +98,28 @@ dependencies {
implementation 'com.google.android.material:material:1.6.0' implementation 'com.google.android.material:material:1.6.0'
implementation platform('com.google.firebase:firebase-bom:30.0.2') implementation platform('com.google.firebase:firebase-bom:30.0.2')
implementation 'com.google.firebase:firebase-analytics' implementation 'com.google.firebase:firebase-analytics'
//Lombok
def lombok_version = "1.18.24"
compileOnly "org.projectlombok:lombok:$lombok_version"
annotationProcessor "org.projectlombok:lombok:$lombok_version"
testCompileOnly "org.projectlombok:lombok:$lombok_version"
testAnnotationProcessor "org.projectlombok:lombok:$lombok_version"
//Database dependencies
def room_version = "2.4.2"
implementation 'net.zetetic:android-database-sqlcipher:4.5.1@aar'
implementation "androidx.sqlite:sqlite:2.2.0"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
// optional - Test helpers
testImplementation "androidx.room:room-testing:$room_version"
//Tests
def test_version = "1.4.0"
testImplementation 'junit:junit:4.13.2'
androidTestImplementation "androidx.test:core:$test_version"
androidTestImplementation "androidx.test:rules:$test_version"
androidTestImplementation "androidx.test:runner:$test_version"
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
} }

View File

@ -0,0 +1,115 @@
package es.ugr.swad.swadroid.dao;
import static junit.framework.TestCase.assertEquals;
import android.database.Cursor;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import es.ugr.swad.swadroid.model.Course;
public class CourseDaoTest extends DaoFixtureTest {
@Before
public void setUp() {
courseDao.insertCourses(COURSES);
}
@Test
public void findAll() {
List<Course> all = courseDao.findAll();
assertEquals(COURSES, all);
}
@Test
public void findAllOrderedByShortNameAsc() {
List<Course> ordered = courseDao.findAllOrderedByShortNameAsc();
List<Course> expected = Arrays.asList(
new Course(2, 1, "c1", "Course 1"),
new Course(1, 1, "c2", "Course 2"),
new Course(3, 1, "c3", "Course 3")
);
assertEquals(expected, ordered);
}
@Test
public void findAllOrderedByShortNameAscCursor() {
Cursor cursor = courseDao.findAllOrderedByShortNameAscCursor();
List<Course> ordered = new ArrayList<>();
List<Course> expected = Arrays.asList(
new Course(1, 1, "c1", "Course 1"),
new Course(2, 1, "c2", "Course 2"),
new Course(3, 1, "c3", "Course 3")
);
int idColNum = cursor.getColumnIndexOrThrow("id");
int userRoleColNum = cursor.getColumnIndexOrThrow("userRole");
int shortNameColNum = cursor.getColumnIndexOrThrow("shortName");
int fullNameColNum = cursor.getColumnIndex("fullName");
while (cursor.moveToNext()) {
long id = cursor.getLong(idColNum);
int userRole = cursor.getInt(userRoleColNum);
String shortName = cursor.getString(shortNameColNum);
String fullName = cursor.getString(fullNameColNum);
ordered.add(new Course(id, userRole, shortName, fullName));
}
assertEquals(expected, ordered);
}
@Test
public void findCourseById() {
Course byId = courseDao.findCourseById(1);
assertEquals(COURSES.get(0), byId);
}
@Test
public void insertCourses() {
List<Course> all = courseDao.findAll();
assertEquals(COURSES, all);
}
@Test
public void updateCourses() {
Course course = new Course(2, 1, "c1", "Course 1 Modified");
courseDao.updateCourses(Collections.singletonList(course));
List<Course> modified = courseDao.findAll();
List<Course> expected = Arrays.asList(
new Course(1, 1, "c2", "Course 2"),
course,
new Course(3, 1, "c3", "Course 3")
);
assertEquals(expected, modified);
}
@Test
public void deleteCourses() {
List<Course> all = courseDao.findAll();
List<Course> expected = COURSES.subList(1, 3);
assertEquals(COURSES, all);
int numDeleted = courseDao.deleteCourses(Collections.singletonList(COURSES.get(0)));
assertEquals(1, numDeleted);
assertEquals(expected, courseDao.findAll());
}
@Test
public void deleteAll() {
List<Course> all = courseDao.findAll();
assertEquals(COURSES, all);
int numDeleted = courseDao.deleteAll();
assertEquals(3, numDeleted);
assertEquals(Collections.EMPTY_LIST, courseDao.findAll());
}
}

View File

@ -0,0 +1,166 @@
package es.ugr.swad.swadroid.dao;
import android.content.Context;
import androidx.room.Room;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import java.util.Arrays;
import java.util.List;
import es.ugr.swad.swadroid.database.AppDatabase;
import es.ugr.swad.swadroid.model.Course;
import es.ugr.swad.swadroid.model.Event;
import es.ugr.swad.swadroid.model.Group;
import es.ugr.swad.swadroid.model.GroupType;
import es.ugr.swad.swadroid.model.SWADNotification;
import es.ugr.swad.swadroid.model.TestAnswer;
import es.ugr.swad.swadroid.model.TestConfig;
import es.ugr.swad.swadroid.model.TestQuestion;
import es.ugr.swad.swadroid.model.TestTag;
import es.ugr.swad.swadroid.model.TestTagsQuestions;
import es.ugr.swad.swadroid.model.User;
import es.ugr.swad.swadroid.model.UserAttendance;
public abstract class DaoFixtureTest {
protected static AppDatabase db;
protected static CourseDao courseDao;
protected static EventDao eventDao;
protected static GroupTypeDao groupTypeDao;
protected static GroupDao groupDao;
protected static UserDao userDao;
protected static UserAttendanceDao userAttendanceDao;
protected static SWADNotificationDao swadNotificationDao;
protected static TestConfigDao testConfigDao;
protected static TestTagDao testTagDao;
protected static TestQuestionDao testQuestionDao;
protected static TestTagsQuestionsDao testTagsQuestionsDao;
protected static TestAnswerDao testAnswerDao;
protected static RawDao rawDao;
private static final long BASE_TIME = System.currentTimeMillis() / 1000;
protected final List<Course> COURSES = Arrays.asList(
new Course(1, 1, "c2", "Course 2"),
new Course(2, 1, "c1", "Course 1"),
new Course(3, 1, "c3", "Course 3")
);
protected final List<Event> EVENTS = Arrays.asList(
new Event(1, 2, false, "", "", "", "", 0L, 0L, false, "Event 2", "Description 2", "", ""),
new Event(2, 1, false, "", "", "", "", 0L, 0L, false, "Event 1", "Description 1", "", ""),
new Event(3, 3, false, "", "", "", "", 0L, 0L, false, "Event 3", "Description 3", "", "")
);
protected final List<UserAttendance> ATTENDANCES = Arrays.asList(
new UserAttendance(1, 2, false),
new UserAttendance(2, 1, false),
new UserAttendance(3, 3, false)
);
protected final List<User> USERS = Arrays.asList(
new User(1, "wsKey", "userID2", "userNickname2", "userSurname1", "userSurname2", "userFirstname", "userPhoto", "20210101", 0),
new User(2, "wsKey", "userID1", "userNickname1", "userSurname1", "userSurname2", "userFirstname", "userPhoto", "20210101", 0),
new User(3, "wsKey", "userID3", "userNickname3", "userSurname1", "userSurname2", "userFirstname", "userPhoto", "20210101", 0)
);
protected final List<GroupType> GROUP_TYPES = Arrays.asList(
new GroupType(1, "Type 2", 2, 0, 0, 0),
new GroupType(2, "Type 1", 1, 0, 0, 0),
new GroupType(3, "Type 3", 3, 0, 0, 0),
new GroupType(4, "Type 4", 1, 0, 0, 0)
);
protected final List<Group> GROUPS = Arrays.asList(
new Group(1, "Group 2", 2, 2, 0, 0, 0, 0, 0),
new Group(2, "Group 1", 1, 1, 0, 0, 0, 0, 0),
new Group(3, "Group 3", 3, 3, 0, 0, 0, 0, 0)
);
protected final List<SWADNotification> NOTIFICATIONS = Arrays.asList(
new SWADNotification(1, 2, "eventType", BASE_TIME, "userNickname", "userSurname1", "userSurname2", "userFirstName", "userPhoto", "location", "summary", 0, "content", true, false),
new SWADNotification(2, 1, "eventType", BASE_TIME - 604800, "userNickname", "userSurname1", "userSurname2", "userFirstName", "userPhoto", "location", "summary", 0, "content", false, false),
new SWADNotification(3, 3, "eventType", BASE_TIME - 86400, "userNickname", "userSurname1", "userSurname2", "userFirstName", "userPhoto", "location", "summary", 0, "content", false, false)
);
protected final List<TestConfig> TEST_CONFIGS = Arrays.asList(
new TestConfig(1, 1, 3, 5, "F1", BASE_TIME),
new TestConfig(2, 1, 3, 5, "F2", BASE_TIME + 1),
new TestConfig(3, 1, 3, 5, "F3", BASE_TIME + 2)
);
protected final List<TestTag> TEST_TAGS = Arrays.asList(
new TestTag(2, "Tag2"),
new TestTag(1, "Tag1"),
new TestTag(3, "Tag3")
);
protected final List<TestQuestion> TEST_QUESTIONS = Arrays.asList(
new TestQuestion(2, 1, "Stem2", TestAnswer.TYPE_TRUE_FALSE, false, "Feedback2"),
new TestQuestion(1, 1, "Stem1", TestAnswer.TYPE_UNIQUE_CHOICE, false, "Feedback1"),
new TestQuestion(3, 1, "Stem3", TestAnswer.TYPE_MULTIPLE_CHOICE, false, "Feedback3"),
new TestQuestion(5, 2, "Stem5", TestAnswer.TYPE_TRUE_FALSE, true, "Feedback5"),
new TestQuestion(4, 2, "Stem4", TestAnswer.TYPE_UNIQUE_CHOICE, true, "Feedback4"),
new TestQuestion(6, 2, "Stem6", TestAnswer.TYPE_MULTIPLE_CHOICE, true, "Feedback6"),
new TestQuestion(8, 3, "Stem8", TestAnswer.TYPE_TRUE_FALSE, false, "Feedback8"),
new TestQuestion(7, 3, "Stem7", TestAnswer.TYPE_UNIQUE_CHOICE, false, "Feedback7"),
new TestQuestion(9, 3, "Stem9", TestAnswer.TYPE_MULTIPLE_CHOICE, false, "Feedback9")
);
protected final List<TestTagsQuestions> TEST_TAGS_QUESTIONS = Arrays.asList(
new TestTagsQuestions(1, 2, 1),
new TestTagsQuestions(2, 2, 1),
new TestTagsQuestions(3, 2, 1),
new TestTagsQuestions(5, 1, 2),
new TestTagsQuestions(4, 1, 2),
new TestTagsQuestions(6, 1, 2),
new TestTagsQuestions(8, 3, 3),
new TestTagsQuestions(7, 3, 3),
new TestTagsQuestions(9, 3, 3)
);
protected final List<TestAnswer> TEST_ANSWERS = Arrays.asList(
new TestAnswer(1, 1, 1, true, "Answer1", "Feedback1"),
new TestAnswer(2, 1, 2, false, "Answer2", "Feedback2"),
new TestAnswer(3, 2, 1, false, "Answer3", "Feedback3"),
new TestAnswer(4, 2, 2, true, "Answer4", "Feedback4"),
new TestAnswer(5, 3, 1, true, "Answer5", "Feedback5"),
new TestAnswer(6, 3, 2, false, "Answer6", "Feedback6"),
new TestAnswer(7, 4, 1, true, "Answer7", "Feedback7"),
new TestAnswer(8, 4, 2, false, "Answer8", "Feedback8"),
new TestAnswer(9, 5, 1, false, "Answer9", "Feedback9"),
new TestAnswer(10, 5, 2, true, "Answer10", "Feedback10"),
new TestAnswer(11, 6, 1, true, "Answer11", "Feedback11"),
new TestAnswer(12, 6, 2, false, "Answer12", "Feedback12"),
new TestAnswer(13, 7, 1, true, "Answer13", "Feedback13"),
new TestAnswer(14, 7, 2, false, "Answer14", "Feedback14"),
new TestAnswer(15, 8, 1, false, "Answer15", "Feedback15"),
new TestAnswer(16, 8, 2, true, "Answer16", "Feedback16"),
new TestAnswer(17, 9, 1, true, "Answer17", "Feedback17"),
new TestAnswer(18, 9, 2, true, "Answer18", "Feedback18")
);
@BeforeClass
public static void setUpClass() {
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
db = Room.inMemoryDatabaseBuilder(context, AppDatabase.class).build();
courseDao = db.getCourseDao();
eventDao = db.getEventDao();
groupTypeDao = db.getGroupTypeDao();
groupDao = db.getGroupDao();
userDao = db.getUserDao();
userAttendanceDao = db.getUserAttendanceDao();
swadNotificationDao = db.getSwadNotificationDao();
testConfigDao = db.getTestConfigDao();
testTagDao = db.getTestTagDao();
testQuestionDao = db.getTestQuestionDao();
testTagsQuestionsDao = db.getTestTagsQuestionsDao();
testAnswerDao = db.getTestAnswerDao();
rawDao = db.getRawDao();
}
@After
public void tearDown() {
db.clearAllTables();
}
@AfterClass
public static void tearDownClass() {
db.close();
}
}

View File

@ -0,0 +1,132 @@
package es.ugr.swad.swadroid.dao;
import static org.junit.Assert.assertEquals;
import android.database.Cursor;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import es.ugr.swad.swadroid.model.Event;
public class EventDaoTest extends DaoFixtureTest {
@Before
public void setUp() {
courseDao.insertCourses(COURSES);
eventDao.insertEvents(EVENTS);
}
@Test
public void findAll() {
List<Event> all = eventDao.findAll();
assertEquals(EVENTS, all);
}
@Test
public void findAllByCourseCode() {
List<Event> events = eventDao.findAllByCourseCode(COURSES.get(0).getId());
List<Event> expected = Collections.singletonList(
new Event(2, 1, false, "", "", "", "", 0L, 0L, false, "Event 1", "Description 1", "", "")
);
assertEquals(expected, events);
}
@Test
public void findAllByCourseCodeCursor() {
Cursor cursor = eventDao.findAllByCourseCodeCursor(COURSES.get(0).getId());
List<Event> ordered = new ArrayList<>();
List<Event> expected = Collections.singletonList(
new Event(2, 1, false, "", "", "", "", 0L, 0L, false, "Event 1", "Description 1", "", "")
);
int idColNum = cursor.getColumnIndexOrThrow("id");
int crsCodColNum = cursor.getColumnIndexOrThrow("crsCod");
int hiddenColNum = cursor.getColumnIndexOrThrow("hidden");
int userSurname1ColNum = cursor.getColumnIndexOrThrow("userSurname1");
int userSurname2ColNum = cursor.getColumnIndex("userSurname2");
int userFirstNameColNum = cursor.getColumnIndex("userFirstName");
int userPhotoColNum = cursor.getColumnIndex("userPhoto");
int startTimeColNum = cursor.getColumnIndex("startTime");
int endTimeColNum = cursor.getColumnIndex("endTime");
int commentsTeachersVisibleColNum = cursor.getColumnIndex("commentsTeachersVisible");
int titleNameColNum = cursor.getColumnIndex("title");
int textNameColNum = cursor.getColumnIndex("text");
int groupsNameColNum = cursor.getColumnIndex("groups");
int statusNameColNum = cursor.getColumnIndex("status");
while (cursor.moveToNext()) {
long id = cursor.getLong(idColNum);
long crsCod = cursor.getLong(crsCodColNum);
boolean hidden = cursor.getInt(hiddenColNum) > 0;
String userSurname1 = cursor.getString(userSurname1ColNum);
String userSurname2 = cursor.getString(userSurname2ColNum);
String userFirstName = cursor.getString(userFirstNameColNum);
String userPhoto = cursor.getString(userPhotoColNum);
long startTime = cursor.getLong(startTimeColNum);
long endTime = cursor.getLong(endTimeColNum);
boolean commentsTeachersVisible = cursor.getInt(commentsTeachersVisibleColNum) > 0;
String title = cursor.getString(titleNameColNum);
String text = cursor.getString(textNameColNum);
String groups = cursor.getString(groupsNameColNum);
String status = cursor.getString(statusNameColNum);
ordered.add(new Event(id, crsCod, hidden, userSurname1, userSurname2, userFirstName, userPhoto, startTime, endTime, commentsTeachersVisible, title, text, groups, status));
}
assertEquals(expected, ordered);
}
@Test
public void findById() {
Event byId = eventDao.findById(1);
assertEquals(EVENTS.get(0), byId);
}
@Test
public void insertEvents() {
List<Event> all = eventDao.findAll();
assertEquals(EVENTS, all);
}
@Test
public void updateEvents() {
Event event = new Event(2, 1, false, "", "", "", "", 0L, 0L, false, "Event 1 Modified", "Description 1 Modified", "", "");
eventDao.updateEvents(Collections.singletonList(event));
List<Event> modified = eventDao.findAll();
List<Event> expected = Arrays.asList(
new Event(1, 2, false, "", "", "", "", 0L, 0L, false, "Event 2", "Description 2", "", ""),
event,
new Event(3, 3, false, "", "", "", "", 0L, 0L, false, "Event 3", "Description 3", "", "")
);
assertEquals(expected, modified);
}
@Test
public void deleteEvents() {
List<Event> all = eventDao.findAll();
List<Event> expected = EVENTS.subList(1, 3);
assertEquals(EVENTS, all);
int numDeleted = eventDao.deleteEvents(Collections.singletonList(EVENTS.get(0)));
assertEquals(1, numDeleted);
assertEquals(expected, eventDao.findAll());
}
@Test
public void deleteAll() {
List<Event> all = eventDao.findAll();
assertEquals(EVENTS, all);
int numDeleted = eventDao.deleteAll();
assertEquals(3, numDeleted);
assertEquals(Collections.EMPTY_LIST, eventDao.findAll());
}
}

View File

@ -0,0 +1,117 @@
package es.ugr.swad.swadroid.dao;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import es.ugr.swad.swadroid.model.Group;
import es.ugr.swad.swadroid.model.GroupsCourse;
import es.ugr.swad.swadroid.model.GroupsGroupType;
public class GroupDaoTest extends DaoFixtureTest {
@Before
public void setUp() {
courseDao.insertCourses(COURSES);
groupTypeDao.insertGroupTypes(GROUP_TYPES);
groupDao.insertGroups(GROUPS);
}
@Test
public void findAll() {
List<Group> all = groupDao.findAll();
assertEquals(GROUPS, all);
}
@Test
public void findAllByTypeCode() {
List<Group> groups = groupDao.findAllByTypeCode(GROUP_TYPES.get(1).getId());
List<Group> expected = Collections.singletonList(
new Group(1, "Group 2", 2, 2, 0, 0, 0, 0, 0)
);
assertEquals(expected, groups);
}
@Test
public void findGroupsGroupTypeByGroupCode() {
GroupsGroupType groupsGroupTypeByGroupCode = groupDao.findGroupsGroupTypeByGroupCode(GROUPS.get(0).getId());
GroupsGroupType expected = new GroupsGroupType();
expected.setGroupType(GROUP_TYPES.get(1));
expected.setGroups(Collections.singletonList(
new Group(1, "Group 2", 2, 2, 0, 0, 0, 0, 0)
));
assertEquals(expected, groupsGroupTypeByGroupCode);
}
@Test
public void findGroupsCourseByCourseCode() {
GroupsCourse groupsCourseByCourseCode = groupDao.findGroupsCourseByCourseCode(COURSES.get(1).getId());
GroupsCourse expected = new GroupsCourse();
expected.setCourse(COURSES.get(1));
expected.setGroups(Collections.singletonList(
new Group(1, "Group 2", 2, 2, 0, 0, 0, 0, 0)
));
assertEquals(expected, groupsCourseByCourseCode);
}
@Test
public void insertGroups() {
List<Group> all = groupDao.findAll();
assertEquals(GROUPS, all);
}
@Test
public void updateGroups() {
Group group = new Group(2, "Group 1 Modified", 1, 1, 0, 0, 0, 0, 0);
groupDao.updateGroups(Collections.singletonList(group));
List<Group> modified = groupDao.findAll();
List<Group> expected = Arrays.asList(
new Group(1, "Group 2", 2, 2, 0, 0, 0, 0, 0),
group,
new Group(3, "Group 3", 3, 3, 0, 0, 0, 0, 0)
);
assertEquals(expected, modified);
}
@Test
public void deleteGroups() {
List<Group> all = groupDao.findAll();
List<Group> expected = GROUPS.subList(1, 3);
assertEquals(GROUPS, all);
int numDeleted = groupDao.deleteGroups(Collections.singletonList(GROUPS.get(0)));
assertEquals(1, numDeleted);
assertEquals(expected, groupDao.findAll());
}
@Test
public void deleteGroupsByIdNotIn() {
List<Group> all = groupDao.findAll();
List<Group> expected = Collections.singletonList(GROUPS.get(0));
assertEquals(GROUPS, all);
int numDeleted = groupDao.deleteGroupsByIdNotIn(Collections.singletonList(GROUPS.get(0).getId()));
assertEquals(2, numDeleted);
assertEquals(expected, groupDao.findAll());
}
@Test
public void deleteAll() {
List<Group> all = groupDao.findAll();
assertEquals(GROUPS, all);
int numDeleted = groupDao.deleteAll();
assertEquals(3, numDeleted);
assertEquals(Collections.EMPTY_LIST, groupDao.findAll());
}
}

View File

@ -0,0 +1,91 @@
package es.ugr.swad.swadroid.dao;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import es.ugr.swad.swadroid.model.GroupType;
public class GroupTypeDaoTest extends DaoFixtureTest {
@Before
public void setUp() {
courseDao.insertCourses(COURSES);
groupTypeDao.insertGroupTypes(GROUP_TYPES);
}
@Test
public void findAll() {
List<GroupType> all = groupTypeDao.findAll();
assertEquals(GROUP_TYPES, all);
}
@Test
public void findAllByCourseCode() {
List<GroupType> groupTypes = groupTypeDao.findAllByCourseCode(COURSES.get(1).getId());
List<GroupType> expected = Collections.singletonList(
new GroupType(1, "Type 2", 2, 0, 0, 0)
);
assertEquals(expected, groupTypes);
}
@Test
public void findAllByCourseCodeOrderByGroupTypeNameAsc() {
List<GroupType> groupTypes = groupTypeDao.findAllByCourseCodeOrderByGroupTypeNameAsc(COURSES.get(0).getId());
List<GroupType> expected = Arrays.asList(
new GroupType(2, "Type 1", 1, 0, 0, 0),
new GroupType(4, "Type 4", 1, 0, 0, 0)
);
assertEquals(expected, groupTypes);
}
@Test
public void insertGroupTypes() {
List<GroupType> all = groupTypeDao.findAll();
assertEquals(GROUP_TYPES, all);
}
@Test
public void updateGroupTypes() {
GroupType groupType = new GroupType(2, "Type 1 Modified", 1, 0, 0, 0);
groupTypeDao.updateGroupTypes(Collections.singletonList(groupType));
List<GroupType> modified = groupTypeDao.findAll();
List<GroupType> expected = Arrays.asList(
new GroupType(1, "Type 2", 2, 0, 0, 0),
groupType,
new GroupType(3, "Type 3", 3, 0, 0, 0),
new GroupType(4, "Type 4", 1, 0, 0, 0)
);
assertEquals(expected, modified);
}
@Test
public void deleteGroupTypes() {
List<GroupType> all = groupTypeDao.findAll();
List<GroupType> expected = GROUP_TYPES.subList(1, 4);
assertEquals(GROUP_TYPES, all);
int numDeleted = groupTypeDao.deleteGroupTypes(Collections.singletonList(GROUP_TYPES.get(0)));
assertEquals(1, numDeleted);
assertEquals(expected, groupTypeDao.findAll());
}
@Test
public void deleteAll() {
List<GroupType> all = groupTypeDao.findAll();
assertEquals(GROUP_TYPES, all);
int numDeleted = groupTypeDao.deleteAll();
assertEquals(4, numDeleted);
assertEquals(Collections.EMPTY_LIST, groupTypeDao.findAll());
}
}

View File

@ -0,0 +1,15 @@
package es.ugr.swad.swadroid.dao;
import static junit.framework.TestCase.assertEquals;
import androidx.sqlite.db.SimpleSQLiteQuery;
import org.junit.Test;
public class RawDaoTest extends DaoFixtureTest {
@Test
public void rawQuery() {
assertEquals(0, rawDao.rawQuery(new SimpleSQLiteQuery("VACUUM")));
}
}

View File

@ -0,0 +1,144 @@
package es.ugr.swad.swadroid.dao;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import es.ugr.swad.swadroid.model.SWADNotification;
public class SWADNotificationDaoTest extends DaoFixtureTest {
@Before
public void setUp() {
swadNotificationDao.insertSWADNotifications(NOTIFICATIONS);
}
@Test
public void findAll() {
List<SWADNotification> all = swadNotificationDao.findAll();
assertEquals(NOTIFICATIONS, all);
}
@Test
public void findAllOrderByEventTimeDesc() {
List<SWADNotification> notifications = swadNotificationDao.findAllOrderByEventTimeDesc(false);
List<SWADNotification> expected = Arrays.asList(
NOTIFICATIONS.get(2),
NOTIFICATIONS.get(1)
);
assertEquals(expected, notifications);
}
@Test
public void findAllPendingToRead() {
List<SWADNotification> notifications = swadNotificationDao.findAllPendingToRead();
List<SWADNotification> expected = Collections.singletonList(
NOTIFICATIONS.get(0)
);
assertEquals(expected, notifications);
}
@Test
public void findById() {
SWADNotification notification = swadNotificationDao.findById(1);
assertEquals(NOTIFICATIONS.get(0), notification);
}
@Test
public void countAll() {
long count = swadNotificationDao.countAll();
assertEquals(3, count);
}
@Test
public void findMaxEventTime() {
long maxEventTime = swadNotificationDao.findMaxEventTime();
assertEquals(NOTIFICATIONS.get(0).getEventTime(), maxEventTime);
}
@Test
public void insertSWADNotifications() {
List<SWADNotification> all = swadNotificationDao.findAll();
assertEquals(NOTIFICATIONS, all);
}
@Test
public void updateSWADNotifications() {
SWADNotification notification = new SWADNotification(2, 1, "eventType", 604800, "userNickname", "userSurname1", "userSurname2", "userFirstName", "userPhoto", "location", "summary", 0, "content", false, false);
swadNotificationDao.updateSWADNotifications(Collections.singletonList(notification));
List<SWADNotification> modified = swadNotificationDao.findAll();
List<SWADNotification> expected = Arrays.asList(
NOTIFICATIONS.get(0),
notification,
NOTIFICATIONS.get(2)
);
assertEquals(expected, modified);
}
@Test
public void updateAllBySeenLocal() {
swadNotificationDao.updateAllBySeenLocal(true);
List<SWADNotification> modified = swadNotificationDao.findAll();
List<SWADNotification> expected = NOTIFICATIONS.stream().peek(n -> n.setSeenLocal(true))
.collect(Collectors.toList());
assertEquals(expected, modified);
}
@Test
public void updateAllBySeenRemote() {
swadNotificationDao.updateAllBySeenRemote(true);
List<SWADNotification> modified = swadNotificationDao.findAll();
List<SWADNotification> expected = NOTIFICATIONS.stream().peek(n -> n.setSeenRemote(true))
.collect(Collectors.toList());
assertEquals(expected, modified);
}
@Test
public void deleteSWADNotifications() {
List<SWADNotification> all = swadNotificationDao.findAll();
List<SWADNotification> expected = NOTIFICATIONS.subList(1, 3);
assertEquals(NOTIFICATIONS, all);
int numDeleted = swadNotificationDao.deleteSWADNotifications(Collections.singletonList(NOTIFICATIONS.get(0)));
assertEquals(1, numDeleted);
assertEquals(expected, swadNotificationDao.findAll());
}
@Test
public void deleteAllByAge() {
List<SWADNotification> all = swadNotificationDao.findAll();
List<SWADNotification> expected = Arrays.asList(
NOTIFICATIONS.get(0),
NOTIFICATIONS.get(2)
);
assertEquals(NOTIFICATIONS, all);
int numDeleted = swadNotificationDao.deleteAllByAge(604800);
assertEquals(1, numDeleted);
assertEquals(expected, swadNotificationDao.findAll());
}
@Test
public void deleteAll() {
List<SWADNotification> all = swadNotificationDao.findAll();
assertEquals(NOTIFICATIONS, all);
int numDeleted = swadNotificationDao.deleteAll();
assertEquals(3, numDeleted);
assertEquals(Collections.EMPTY_LIST, swadNotificationDao.findAll());
}
}

View File

@ -0,0 +1,86 @@
package es.ugr.swad.swadroid.dao;
import static junit.framework.TestCase.assertEquals;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import es.ugr.swad.swadroid.model.Model;
import es.ugr.swad.swadroid.model.TestAnswer;
public class TestAnswerDaoTest extends DaoFixtureTest {
private final Comparator<TestAnswer> compareById = Comparator.comparingLong(Model::getId);
@Before
public void setUp() {
courseDao.insertCourses(COURSES);
testTagDao.insertTestTag(TEST_TAGS);
testQuestionDao.insertTestQuestion(TEST_QUESTIONS);
testTagsQuestionsDao.insertTestTagQuestion(TEST_TAGS_QUESTIONS);
testAnswerDao.insertTestAnswer(TEST_ANSWERS);
}
@Test
public void findAll() {
List<TestAnswer> all = testAnswerDao.findAll();
assertEquals(TEST_ANSWERS, all);
}
@Test
public void insertTestAnswer() {
List<TestAnswer> all = testAnswerDao.findAll();
assertEquals(TEST_ANSWERS, all);
}
@Test
public void updateTestAnswer() {
TestAnswer testAnswer = new TestAnswer(2, 1, 2, false, "Answer2 Modified", "Feedback2");
testAnswerDao.updateTestAnswer(Collections.singletonList(testAnswer));
List<TestAnswer> modified = testAnswerDao.findAll();
List<TestAnswer> expected = new ArrayList<>(TEST_ANSWERS);
modified.sort(compareById);
expected.sort(compareById);
expected.set(1, testAnswer);
assertEquals(expected, modified);
}
@Test
public void deleteTestAnswer() {
List<TestAnswer> all = testAnswerDao.findAll();
List<TestAnswer> expected = new ArrayList<>(TEST_ANSWERS);
List<TestAnswer> allSorted = new ArrayList<>(TEST_ANSWERS);
expected.sort(compareById);
allSorted.sort(compareById);
TestAnswer deleted = expected.remove(1);
assertEquals(allSorted, all);
int numDeleted = testAnswerDao.deleteTestAnswer(Collections.singletonList(deleted));
assertEquals(1, numDeleted);
assertEquals(expected, testAnswerDao.findAll());
}
@Test
public void deleteAll() {
List<TestAnswer> all = testAnswerDao.findAll();
List<TestAnswer> expected = new ArrayList<>(TEST_ANSWERS);
expected.sort(compareById);
assertEquals(expected, all);
int numDeleted = testAnswerDao.deleteAll();
assertEquals(18, numDeleted);
assertEquals(Collections.EMPTY_LIST, testAnswerDao.findAll());
}
}

View File

@ -0,0 +1,105 @@
package es.ugr.swad.swadroid.dao;
import static junit.framework.TestCase.assertEquals;
import android.database.Cursor;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import es.ugr.swad.swadroid.model.TestConfig;
public class TestConfigDaoTest extends DaoFixtureTest {
@Before
public void setUp() {
testConfigDao.insertTestConfig(TEST_CONFIGS);
}
@Test
public void findAll() {
List<TestConfig> all = testConfigDao.findAll();
assertEquals(TEST_CONFIGS, all);
}
@Test
public void findByCourseCode() {
TestConfig byId = testConfigDao.findByCourseCode(1);
assertEquals(TEST_CONFIGS.get(0), byId);
}
@Test
public void findCursorByCourseCode() {
Cursor cursor = testConfigDao.findCursorByCourseCode(1);
List<TestConfig> ordered = new ArrayList<>();
List<TestConfig> expected = Collections.singletonList(
TEST_CONFIGS.get(0)
);
int idColNum = cursor.getColumnIndexOrThrow("id");
int minColNum = cursor.getColumnIndexOrThrow("min");
int defColNum = cursor.getColumnIndexOrThrow("def");
int maxColNum = cursor.getColumnIndex("max");
int feedbackColNum = cursor.getColumnIndex("feedback");
int editTimeColNum = cursor.getColumnIndex("editTime");
while (cursor.moveToNext()) {
long id = cursor.getLong(idColNum);
int min = cursor.getInt(minColNum);
int def = cursor.getInt(defColNum);
int max = cursor.getInt(maxColNum);
String feedback = cursor.getString(feedbackColNum);
long editTime = cursor.getLong(editTimeColNum);
ordered.add(new TestConfig(id, min, def, max, feedback, editTime));
}
assertEquals(expected, ordered);
}
@Test
public void insertTestConfig() {
List<TestConfig> all = testConfigDao.findAll();
assertEquals(TEST_CONFIGS, all);
}
@Test
public void updateTestConfig() {
TestConfig testConfig = new TestConfig(2, 1, 3, 5, "F2 Modified", 0L);
testConfigDao.updateTestConfig(Collections.singletonList(testConfig));
List<TestConfig> modified = testConfigDao.findAll();
List<TestConfig> expected = Arrays.asList(
TEST_CONFIGS.get(0),
testConfig,
TEST_CONFIGS.get(2)
);
assertEquals(expected, modified);
}
@Test
public void deleteTestConfig() {
List<TestConfig> all = testConfigDao.findAll();
List<TestConfig> expected = TEST_CONFIGS.subList(1, 3);
assertEquals(TEST_CONFIGS, all);
int numDeleted = testConfigDao.deleteTestConfig(Collections.singletonList(TEST_CONFIGS.get(0)));
assertEquals(1, numDeleted);
assertEquals(expected, testConfigDao.findAll());
}
@Test
public void deleteAll() {
List<TestConfig> all = testConfigDao.findAll();
assertEquals(TEST_CONFIGS, all);
int numDeleted = testConfigDao.deleteAll();
assertEquals(3, numDeleted);
assertEquals(Collections.EMPTY_LIST, testConfigDao.findAll());
}
}

View File

@ -0,0 +1,153 @@
package es.ugr.swad.swadroid.dao;
import static junit.framework.Assert.assertTrue;
import static junit.framework.TestCase.assertEquals;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import es.ugr.swad.swadroid.model.Model;
import es.ugr.swad.swadroid.model.TestAnswer;
import es.ugr.swad.swadroid.model.TestAnswersQuestion;
import es.ugr.swad.swadroid.model.TestQuestion;
import es.ugr.swad.swadroid.model.TestTag;
public class TestQuestionDaoTest extends DaoFixtureTest {
private final Comparator<TestQuestion> testQuestionComparator = Comparator.comparingLong(Model::getId);
private final Comparator<TestAnswer> testAnswerComparator = Comparator.comparingLong(Model::getId);
@Before
public void setUp() throws Exception {
courseDao.insertCourses(COURSES);
testTagDao.insertTestTag(TEST_TAGS);
testQuestionDao.insertTestQuestion(TEST_QUESTIONS);
testTagsQuestionsDao.insertTestTagQuestion(TEST_TAGS_QUESTIONS);
testAnswerDao.insertTestAnswer(TEST_ANSWERS);
}
@Test
public void findAll() {
List<TestQuestion> all = testQuestionDao.findAll();
List<TestQuestion> expected = TEST_QUESTIONS;
expected.sort(testQuestionComparator);
assertEquals(expected, all);
}
@Test
public void findAllCourseQuestionsOrderByRandomAndAnswerIndex() {
int crsCod = 1;
List<Long> questions = TEST_QUESTIONS.stream().filter(t -> t.getCrsCod() == crsCod).map(TestQuestion::getId).collect(Collectors.toList());
TestAnswersQuestion answersQuestion = testQuestionDao.findAllCourseQuestionsOrderByRandomAndAnswerIndex(crsCod, 1).get(0);
answersQuestion.getTestAnswers().sort(testAnswerComparator);
assertTrue(questions.contains(answersQuestion.getTestQuestion().getId()));
assertEquals(TEST_ANSWERS.stream().filter(a -> a.getQstCod() == answersQuestion.getTestQuestion().getId()).collect(Collectors.toList()),
answersQuestion.getTestAnswers());
}
@Test
public void findAllCourseQuestionsByTagOrderByRandomAndAnswerIndex() {
int crsCod = 1;
List<String> tags = TEST_TAGS.stream().map(TestTag::getTagTxt).collect(Collectors.toList());
List<Long> questions = TEST_QUESTIONS.stream().filter(t -> t.getCrsCod() == crsCod).map(TestQuestion::getId).collect(Collectors.toList());
TestAnswersQuestion answersQuestion = testQuestionDao.findAllCourseQuestionsByTagOrderByRandomAndAnswerIndex(crsCod, tags, 1).get(0);
answersQuestion.getTestAnswers().sort(testAnswerComparator);
assertTrue(questions.contains(answersQuestion.getTestQuestion().getId()));
assertEquals(TEST_ANSWERS.stream().filter(a -> a.getQstCod() == answersQuestion.getTestQuestion().getId()).collect(Collectors.toList()),
answersQuestion.getTestAnswers());
}
@Test
public void findAllCourseQuestionsByAnswerTypeOrderByRandomAndAnswerIndex() {
int crsCod = 1;
List<String> answerTypes = Collections.singletonList(TestAnswer.TYPE_TRUE_FALSE);
List<Long> questions = TEST_QUESTIONS.stream().filter(t -> t.getCrsCod() == crsCod).map(TestQuestion::getId).collect(Collectors.toList());
TestAnswersQuestion answersQuestion = testQuestionDao.findAllCourseQuestionsByAnswerTypeOrderByRandomAndAnswerIndex(crsCod, answerTypes, 1).get(0);
answersQuestion.getTestAnswers().sort(testAnswerComparator);
assertTrue(questions.contains(answersQuestion.getTestQuestion().getId()));
assertEquals(TEST_ANSWERS.stream().filter(a -> a.getQstCod() == answersQuestion.getTestQuestion().getId()).collect(Collectors.toList()),
answersQuestion.getTestAnswers());
}
@Test
public void findAllCourseQuestionsByTagAndAnswerTypeOrderByRandomAndAnswerIndex() {
int crsCod = 1;
List<String> tags = TEST_TAGS.stream().map(TestTag::getTagTxt).collect(Collectors.toList());
List<String> answerTypes = Arrays.asList(TestAnswer.TYPE_UNIQUE_CHOICE, TestAnswer.TYPE_MULTIPLE_CHOICE);
List<Long> questions = TEST_QUESTIONS.stream().filter(t -> t.getCrsCod() == crsCod).map(TestQuestion::getId).collect(Collectors.toList());
TestAnswersQuestion answersQuestion = testQuestionDao.findAllCourseQuestionsByTagAndAnswerTypeOrderByRandomAndAnswerIndex(crsCod, tags, answerTypes, 1).get(0);
answersQuestion.getTestAnswers().sort(testAnswerComparator);
assertTrue(questions.contains(answersQuestion.getTestQuestion().getId()));
assertEquals(TEST_ANSWERS.stream().filter(a -> a.getQstCod() == answersQuestion.getTestQuestion().getId()).collect(Collectors.toList()),
answersQuestion.getTestAnswers());
}
@Test
public void insertTestQuestion() {
List<TestQuestion> all = testQuestionDao.findAll();
List<TestQuestion> expected = TEST_QUESTIONS;
expected.sort(testQuestionComparator);
assertEquals(expected, all);
}
@Test
public void updateTestQuestion() {
TestQuestion testQuestion = new TestQuestion(1, 1, "Stem1 Modified", "TF", false, "Feedback1");
testQuestionDao.updateTestQuestion(Collections.singletonList(testQuestion));
List<TestQuestion> modified = testQuestionDao.findAll();
List<TestQuestion> expected = new ArrayList<>(TEST_QUESTIONS);
modified.sort(testQuestionComparator);
expected.sort(testQuestionComparator);
expected.set(0, testQuestion);
assertEquals(expected, modified);
}
@Test
public void deleteTestQuestion() {
List<TestQuestion> all = testQuestionDao.findAll();
List<TestQuestion> expected = new ArrayList<>(TEST_QUESTIONS);
List<TestQuestion> allSorted = new ArrayList<>(TEST_QUESTIONS);
expected.sort(testQuestionComparator);
allSorted.sort(testQuestionComparator);
TestQuestion deleted = expected.remove(1);
assertEquals(allSorted, all);
int numDeleted = testQuestionDao.deleteTestQuestion(Collections.singletonList(deleted));
assertEquals(1, numDeleted);
assertEquals(expected, testQuestionDao.findAll());
}
@Test
public void deleteAll() {
List<TestQuestion> all = testQuestionDao.findAll();
List<TestQuestion> expected = new ArrayList<>(TEST_QUESTIONS);
expected.sort(testQuestionComparator);
assertEquals(expected, all);
int numDeleted = testQuestionDao.deleteAll();
assertEquals(9, numDeleted);
assertEquals(Collections.EMPTY_LIST, testQuestionDao.findAll());
}
}

View File

@ -0,0 +1,82 @@
package es.ugr.swad.swadroid.dao;
import static junit.framework.TestCase.assertEquals;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import es.ugr.swad.swadroid.model.Model;
import es.ugr.swad.swadroid.model.TestTag;
public class TestTagDaoTest extends DaoFixtureTest {
private final Comparator<TestTag> compareById = Comparator.comparingLong(Model::getId);
@Before
public void setUp() {
testTagDao.insertTestTag(TEST_TAGS);
}
@Test
public void findAll() {
List<TestTag> all = testTagDao.findAll();
List<TestTag> expected = TEST_TAGS;
expected.sort(compareById);
assertEquals(expected, all);
}
@Test
public void insertTestTag() {
List<TestTag> all = testTagDao.findAll();
List<TestTag> expected = TEST_TAGS;
expected.sort(compareById);
assertEquals(expected, all);
}
@Test
public void updateTestTag() {
TestTag TestTag = new TestTag(1, "Tag 1 Modified");
testTagDao.updateTestTag(Collections.singletonList(TestTag));
List<TestTag> modified = testTagDao.findAll();
List<TestTag> expected = Arrays.asList(
TestTag,
TEST_TAGS.get(0),
TEST_TAGS.get(2)
);
assertEquals(expected, modified);
}
@Test
public void deleteTestTag() {
List<TestTag> all = testTagDao.findAll();
List<TestTag> expected = TEST_TAGS.subList(1, 3);
List<TestTag> allSorted = TEST_TAGS;
expected.sort(compareById);
allSorted.sort(compareById);
assertEquals(allSorted, all);
int numDeleted = testTagDao.deleteTestTag(Collections.singletonList(TEST_TAGS.get(0)));
assertEquals(1, numDeleted);
assertEquals(expected, testTagDao.findAll());
}
@Test
public void deleteAll() {
List<TestTag> all = testTagDao.findAll();
List<TestTag> expected = TEST_TAGS;
expected.sort(compareById);
assertEquals(expected, all);
int numDeleted = testTagDao.deleteAll();
assertEquals(3, numDeleted);
assertEquals(Collections.EMPTY_LIST, testTagDao.findAll());
}
}

View File

@ -0,0 +1,75 @@
package es.ugr.swad.swadroid.dao;
import static junit.framework.TestCase.assertEquals;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import es.ugr.swad.swadroid.model.TestTagsQuestions;
public class TestTagsQuestionsDaoTest extends DaoFixtureTest {
@Before
public void setUp() {
courseDao.insertCourses(COURSES);
testTagDao.insertTestTag(TEST_TAGS);
testQuestionDao.insertTestQuestion(TEST_QUESTIONS);
testTagsQuestionsDao.insertTestTagQuestion(TEST_TAGS_QUESTIONS);
testAnswerDao.insertTestAnswer(TEST_ANSWERS);
}
@Test
public void findAll() {
List<TestTagsQuestions> all = testTagsQuestionsDao.findAll();
assertEquals(TEST_TAGS_QUESTIONS, all);
}
@Test
public void insertTestTagsQuestions() {
List<TestTagsQuestions> all = testTagsQuestionsDao.findAll();
assertEquals(TEST_TAGS_QUESTIONS, all);
}
@Test
public void updateTestTagsQuestions() {
TestTagsQuestions testTagQuestions = new TestTagsQuestions(2, 2, 2);
testTagsQuestionsDao.updateTestTagQuestion(Collections.singletonList(testTagQuestions));
List<TestTagsQuestions> modified = testTagsQuestionsDao.findAll();
List<TestTagsQuestions> expected = new ArrayList<>(TEST_TAGS_QUESTIONS);
expected.set(1, testTagQuestions);
assertEquals(expected, modified);
}
@Test
public void deleteTestTagsQuestions() {
List<TestTagsQuestions> all = testTagsQuestionsDao.findAll();
List<TestTagsQuestions> expected = new ArrayList<>(TEST_TAGS_QUESTIONS);
List<TestTagsQuestions> allSorted = new ArrayList<>(TEST_TAGS_QUESTIONS);
TestTagsQuestions deleted = expected.remove(1);
assertEquals(allSorted, all);
int numDeleted = testTagsQuestionsDao.deleteTestTagQuestion(Collections.singletonList(deleted));
assertEquals(1, numDeleted);
assertEquals(expected, testTagsQuestionsDao.findAll());
}
@Test
public void deleteAll() {
List<TestTagsQuestions> all = testTagsQuestionsDao.findAll();
List<TestTagsQuestions> expected = new ArrayList<>(TEST_TAGS_QUESTIONS);
assertEquals(expected, all);
int numDeleted = testTagsQuestionsDao.deleteAll();
assertEquals(9, numDeleted);
assertEquals(Collections.EMPTY_LIST, testTagsQuestionsDao.findAll());
}
}

View File

@ -0,0 +1,99 @@
package es.ugr.swad.swadroid.dao;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import es.ugr.swad.swadroid.model.UserAttendance;
public class UserAttendanceDaoTest extends DaoFixtureTest {
@Before
public void setUp() {
courseDao.insertCourses(COURSES);
eventDao.insertEvents(EVENTS);
userDao.insertUsers(USERS);
userAttendanceDao.insertAttendances(ATTENDANCES);
}
@Test
public void findAll() {
List<UserAttendance> all = userAttendanceDao.findAll();
assertEquals(ATTENDANCES, all);
}
@Test
public void findByEventCode() {
List<UserAttendance> attendances = userAttendanceDao.findByEventCode(EVENTS.get(1).getId());
List<UserAttendance> expected = Collections.singletonList(
new UserAttendance(1, 2, false)
);
assertEquals(expected, attendances);
}
@Test
public void findByUserCodeAndEventCode() {
UserAttendance attendance = userAttendanceDao.findByUserCodeAndEventCode(USERS.get(0).getId(), EVENTS.get(1).getId());
UserAttendance expected = new UserAttendance(1, 2, false);
assertEquals(expected, attendance);
}
@Test
public void insertAttendances() {
List<UserAttendance> all = userAttendanceDao.findAll();
assertEquals(ATTENDANCES, all);
}
@Test
public void updateAttendances() {
UserAttendance attendance = new UserAttendance(2, 1, true);
userAttendanceDao.updateAttendances(Collections.singletonList(attendance));
List<UserAttendance> modified = userAttendanceDao.findAll();
List<UserAttendance> expected = Arrays.asList(
new UserAttendance(1, 2, false),
attendance,
new UserAttendance(3, 3, false)
);
assertEquals(expected, modified);
}
@Test
public void deleteAttendances() {
List<UserAttendance> all = userAttendanceDao.findAll();
List<UserAttendance> expected = ATTENDANCES.subList(1, 3);
assertEquals(ATTENDANCES, all);
int numDeleted = userAttendanceDao.deleteAttendances(Collections.singletonList(ATTENDANCES.get(0)));
assertEquals(1, numDeleted);
assertEquals(expected, userAttendanceDao.findAll());
}
@Test
public void deleteAttendancesByEventCode() {
List<UserAttendance> all = userAttendanceDao.findAll();
List<UserAttendance> expected = ATTENDANCES.subList(1, 3);
assertEquals(ATTENDANCES, all);
int numDeleted = userAttendanceDao.deleteAttendancesByEventCode(EVENTS.get(1).getId());
assertEquals(1, numDeleted);
assertEquals(expected, userAttendanceDao.findAll());
}
@Test
public void deleteAll() {
List<UserAttendance> all = userAttendanceDao.findAll();
assertEquals(ATTENDANCES, all);
int numDeleted = userAttendanceDao.deleteAll();
assertEquals(3, numDeleted);
assertEquals(Collections.EMPTY_LIST, userAttendanceDao.findAll());
}
}

View File

@ -0,0 +1,118 @@
package es.ugr.swad.swadroid.dao;
import static org.junit.Assert.assertEquals;
import android.database.Cursor;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import es.ugr.swad.swadroid.model.User;
public class UserDaoTest extends DaoFixtureTest {
@Before
public void setUp() {
courseDao.insertCourses(COURSES);
eventDao.insertEvents(EVENTS);
userDao.insertUsers(USERS);
userAttendanceDao.insertAttendances(ATTENDANCES);
}
@Test
public void findAll() {
List<User> all = userDao.findAll();
assertEquals(USERS, all);
}
@Test
public void findAllByEventCodeCursor() {
Cursor cursor = userDao.findAllByEventCodeCursor(EVENTS.get(0).getId());
List<User> ordered = new ArrayList<>();
List<User> expected = Collections.singletonList(
new User(2, "wsKey", "userID1", "userNickname1", "userSurname1", "userSurname2", "userFirstname", "userPhoto", "20210101", 0)
);
int idColNum = cursor.getColumnIndexOrThrow("id");
int wsKeyColNum = cursor.getColumnIndexOrThrow("wsKey");
int userIDColNum = cursor.getColumnIndexOrThrow("userID");
int userNicknameColNum = cursor.getColumnIndexOrThrow("userNickname");
int userSurname1ColNum = cursor.getColumnIndex("userSurname1");
int userSurname2ColNum = cursor.getColumnIndex("userSurname2");
int userFirstNameColNum = cursor.getColumnIndex("userFirstname");
int userPhotoColNum = cursor.getColumnIndex("userPhoto");
int userBirthdayColNum = cursor.getColumnIndex("userBirthday");
int userRoleColNum = cursor.getColumnIndex("userRole");
while (cursor.moveToNext()) {
long id = cursor.getLong(idColNum);
String wsKey = cursor.getString(wsKeyColNum);
String userID = cursor.getString(userIDColNum);
String userNickname = cursor.getString(userNicknameColNum);
String userSurname1 = cursor.getString(userSurname1ColNum);
String userSurname2 = cursor.getString(userSurname2ColNum);
String userFirstName = cursor.getString(userFirstNameColNum);
String userPhoto = cursor.getString(userPhotoColNum);
String userBirthday = cursor.getString(userBirthdayColNum);
int userRole = cursor.getInt(userRoleColNum);
ordered.add(new User(id, wsKey, userID, userNickname, userSurname1, userSurname2, userFirstName, userPhoto, userBirthday, userRole));
}
assertEquals(expected, ordered);
}
@Test
public void findUserByUserNickname() {
User user = userDao.findUserByUserNickname(USERS.get(0).getUserNickname());
User expected = USERS.get(0);
assertEquals(expected, user);
}
@Test
public void insertUsers() {
List<User> all = userDao.findAll();
assertEquals(USERS, all);
}
@Test
public void updateUsers() {
User user = new User(2, "wsKey", "userID1 Modified", "userNickname1", "userSurname1", "userSurname2", "userFirstname", "userPhoto", "20210101", 0);
userDao.updateUsers(Collections.singletonList(user));
List<User> modified = userDao.findAll();
List<User> expected = Arrays.asList(
new User(1, "wsKey", "userID2", "userNickname2", "userSurname1", "userSurname2", "userFirstname", "userPhoto", "20210101", 0),
user,
new User(3, "wsKey", "userID3", "userNickname3", "userSurname1", "userSurname2", "userFirstname", "userPhoto", "20210101", 0)
);
assertEquals(expected, modified);
}
@Test
public void deleteUsers() {
List<User> all = userDao.findAll();
List<User> expected = USERS.subList(1, 3);
assertEquals(USERS, all);
int numDeleted = userDao.deleteUsers(Collections.singletonList(USERS.get(0)));
assertEquals(1, numDeleted);
assertEquals(expected, userDao.findAll());
}
@Test
public void deleteAll() {
List<User> all = userDao.findAll();
assertEquals(USERS, all);
int numDeleted = userDao.deleteAll();
assertEquals(3, numDeleted);
assertEquals(Collections.EMPTY_LIST, userDao.findAll());
}
}

View File

@ -1,6 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="es.ugr.swad.swadroid"
android:installLocation="auto" > android:installLocation="auto" >
<!-- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <!-- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

View File

@ -1,545 +0,0 @@
/*
* Copyright (C) 2008 Javier Perez Pacheco y Javier Ros Moreno
*
* Android Data Framework: Trabajo con BD SQLite en Android
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Javier Perez Pacheco
* Cadiz (Spain)
* javi.pacheco@gmail.com
*
* Javier Ros Moreno
* jros@jros.org
*
*
*/
package com.android.dataframework;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.android.dataframework.core.DataFrameworkCore;
import com.android.dataframework.core.Table;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.util.ArrayList;
public class DataFramework {
public final static String VERSION = "1.02";
public final static String KEY_ID = "_id";
public static DataFramework mDataFramework = null;
private int mOpenInstances = 0;
private ArrayList<Table> mTables = new ArrayList<>();
private DataFrameworkCore mCore;
public void open(Context context, String namePackage) throws XmlPullParserException, IOException
{
if (mOpenInstances == 0){
mCore.open(context, namePackage, mTables);
}
mOpenInstances++;
}
public void close()
{
if(mOpenInstances>0){
mOpenInstances--;
}
if (mOpenInstances == 0){
mCore.close();
}
}
/**
* Constructor privado, usamos el modelo Singletone.
*/
private DataFramework()
{
mCore = new DataFrameworkCore();
}
/**
* Devuelve la instancia de la clase, si no existe la crea.
*
* @return DataFramework
*/
public static DataFramework getInstance()
{
if (mDataFramework == null)
{
mDataFramework = new DataFramework();
}
return mDataFramework;
}
/**
* Devuelve un objeto Table del nombre de la tabla pasado como par<EFBFBD>metro
*
* @param table el nombre de la tabla
*
* @return objeto Table
*/
public Table getTable (String table) throws NullPointerException {
Table res = null;
ArrayList<Table> tables = mTables;
int tableCount = tables.size();
for (int i = 0; i < tableCount; i++)
{
Table t = tables.get(i);
if (t.getName().equals(table)){
res = t;
}
}
if(res==null){
throw new NullPointerException("No existe la tabla '"+table+"'");
}
return res;
}
/**
* Devuelve el numero de tablas de la base de datos
*
* @return objeto Numero de tablas
*/
public int getTableCount () {
return mTables.size();
}
public Context getContext()
{
return mCore.getContext();
}
public String getPackage() {
return mCore.getPackage();
}
/**
* Devuelve un valor de un identificador
*
* @param name Nombre del identificador
*
* @return valor
*/
public String getStringFromIdentifier (String name) {
int id = mCore.getContext().getResources().getIdentifier(mCore.getPackage() + ":string/"+name, null, null);
if (id!=0){
return mCore.getContext().getResources().getString(id);
}else{
return name;
}
}
/**
* Devuelve una lista con todos los objetos Entity de la tabla
*
* @param table tabla a usar
*
* @return lista de objetos
*/
public ArrayList<Entity> getEntityList(String table) {
return getEntityList(table, null, null, null);
}
/**
* Devuelve una lista los objetos Entity de la tabla de una consulta
*
* @param table tabla a usar
* @param where parte WHERE de la consulta SQL
*
* @return lista de objetos
*/
public ArrayList<Entity> getEntityList(String table, String where) {
return getEntityList(table, where, null, null);
}
/**
* Devuelve una lista los objetos Entity de la tabla de una consulta
*
* @param table tabla a usar
* @param where parte WHERE de la consulta SQL
* @param orderby parte ORDER BY de la consulta SQL
*
* @return lista de objetos
*/
public ArrayList<Entity> getEntityList(String table, String where, String orderby) {
return getEntityList(table, where, orderby, null);
}
/**
* Devuelve una lista los objetos Entity de la tabla de una consulta ordenados
*
* @param table tabla a usar
* @param where parte WHERE de la consulta SQL
* @param orderby parte ORDER BY de la consulta SQL
* @param limit parte LIMIT de la consulta SQL
*
* @return lista de objetos
*/
public ArrayList<Entity> getEntityList(String table, String where, String orderby, String limit) {
String[] fields = getTable(table).getFieldsToArray();
Cursor c = getCursor(table, fields, where, null, null, null, orderby, limit);
ArrayList<Entity> aux = new ArrayList<>();
c.moveToFirst();
while (!c.isAfterLast()) {
// Creamos la entidad a partir del cursor y nos ahorramos el acceso a la BD
Entity ent = new Entity(table, c);
aux.add(ent);
c.moveToNext();
}
c.close();
return aux;
}
/**
* Devuelve el primer resultado de la consulta
*
* @param table tabla a usar
* @param where parte WHERE de la consulta SQL
* @param orderby parte ORDER BY de la consulta SQL
* @param limit parte LIMIT de la consulta SQL
*
* @return lista de objetos
*/
public Entity getTopEntity(String table, String where, String orderby) {
ArrayList<Entity> ar = getEntityList(table, where, orderby, "1");
if (ar.size()>0) {
return ar.get(0);
} else {
return null;
}
}
/**
* Devuelve el numero de resultados de una consulta
*
* @param table tabla a usar
* @param where parte WHERE de la consulta SQL
*
* @return numero de objetos
*/
public int getEntityListCount(String table, String where) {
String[] fields = getTable(table).getFieldsToArray();
Cursor c = getCursor(table, fields, where, null, null, null, null, null);
int count = c.getCount();
c.close();
c = null;
return count;
}
/**
* Devuelve la posicion de un identificador en una lista de Entidades
*
* @param ar lista de entidades
* @param id identificador a buscar
*
* @return posicion
*/
public int getPosition(ArrayList<Entity> ar, long id)
{
int size = ar.size();
for (int i=0; i<size; i++) {
if ( ar.get(i).getId() == id ) {
return i;
}
}
return -1;
}
/**
* Devuelve un cursor con todos los registros de la tabla
*
* @param table tabla a usar
*
* @return cursor
*/
public Cursor getCursor(String table) {
String[] aux = getTable(table).getFieldsToArray();
return mCore.getDB().query(table, aux, null, null, null, null, null);
}
/**
* Devuelve un cursor con los registros de una consulta en la tabla
*
* @param table tabla a usar
* @param selection parte WHERE de la consulta SQL
* @param orderby parte ORDER BY de la consulta SQL
*
* @return cursor
*/
public Cursor getCursor(String table, String selection, String orderby) {
String[] aux = getTable(table).getFieldsToArray();
return mCore.getDB().query(table, aux, selection, null, null, null, orderby, null);
}
/**
* Devuelve un cursor con los registros de una consulta en la tabla
*
* @param table tabla a usar
* @param fields array con los nombres de los campos de la tabla
* @param selection parte WHERE de la consulta SQL
* @param selectionArgs array
* @param groupby parte GROUP BY de la consulta SQL
* @param having parte HAVING de la consulta SQL
* @param orderby parte ORDER BY de la consulta SQL
* @param limit parte LIMIT de la consulta SQL
*
* @return cursor
*/
public Cursor getCursor(String table, String[] fields, String selection,
String[] selectionArgs, String groupby, String having, String orderby, String limit) {
return mCore.getDB().query(table, fields, selection, selectionArgs, groupby, having, orderby, limit);
}
/**
* Devuelve un cursor con los registros de una consulta en la tabla
*
* @param sql consulta SQL
* @param selectionArgs array
*
* @return lista de objetos
*/
public Cursor rawQuery(String sql, String[] selectionArgs) {
Cursor c = mCore.getDB().rawQuery(sql, selectionArgs);
if (c.getCount() > 0) {
c.moveToFirst();
}
return c;
}
/**
* Crea las tablas de la base de datos
*
*/
public void createTables() {
ArrayList<Table> tables = mTables;
int tableCount = tables.size();
for (int i = 0; i < tableCount; i++){
mCore.getDB().execSQL(tables.get(i).getSQLCreateTable());
}
}
/**
* Borra todas las tablas de la base de datos
*
*/
public void deleteTables() {
ArrayList<Table> tables = mTables;
int tableCount = tables.size();
for (int i = 0; i < tableCount; i++){
mCore.getDB().execSQL(tables.get(i).getSQLDeleteTable());
}
}
/**
* Borra la tabla pasada como parametro de la base de datos
*
* @param table tabla
*
*/
public void deleteTable(String table) {
Table t = getTable(table);
if (t != null){
mCore.getDB().execSQL(t.getSQLDeleteTable());
}
}
/**
* Vacia todas las tablas de la base de datos
*
*/
public void emptyTables() {
ArrayList<Table> tables = mTables;
int tableCount = tables.size();
for (int i = 0; i < tableCount; i++){
mCore.getDB().delete(tables.get(i).getName(), null, null);
}
}
/**
* Vacia todas las tablas que formen parte del backup
*
*/
public void emptyTablesBackup() {
ArrayList<Table> tables = mTables;
int tableCount = tables.size();
for (int i = 0; i < tableCount; i++)
{
Table t = tables.get(i);
if (t.isBackup()){
mCore.getDB().delete(t.getName(), null, null);
}
}
}
/**
* Vacia la tabla pasada como parametro de la base de datos
*
* @param table tabla
*
*/
public void emptyTable(String table) {
mCore.getDB().delete(table, null, null);
}
/**
* Crea una copia de seguridad de la base de datos
*
* @param file Archivo XML donde hace la copia
*
*/
public void backup(String file) throws XmlPullParserException, IOException {
mCore.backup(file, false);
}
/**
* Crea una copia de seguridad de la base de datos
*
* @param file Archivo XML donde hace la copia
* @param forceBackup Forzar a hacer backup aunque la table no lo permita
*
*/
public void backup(String file, boolean forceBackup) throws XmlPullParserException, IOException {
mCore.backup(file, forceBackup);
}
/**
* Reestablece una copia de seguridad de la base de datos
*
* @param file Archivo XML donde esta la copia
*
*/
public void restore(String file) throws XmlPullParserException, IOException {
mCore.restore(file);
}
/**
* Devuelve un cursor del tipo EntityCursor
*
* @param table Tabla
* @param where Condicion de busqueda
* @param orderby Ordenacion
* @return Cursor de entidades.
*/
public EntityCursor getEntityCursor(String table, String where, String orderby) {
String[] fields = getTable(table).getFieldsToArray();
Cursor c = getCursor(table, fields, where, null, null, null, orderby, null);
return new EntityCursor(table, c);
}
/**
* Devuelve conexion a SQLiteDatabase
*
* @return objeto SQLiteDatabase
*/
public SQLiteDatabase getDB() {
return mCore.getDB();
}
public void setForceLanguage(String lang) {
mCore.setForceLanguage(lang);
}
public ArrayList<String> getLanguages() {
return mCore.getLanguages();
}
public String getCurrentLanguage() {
return mCore.getCurrentLanguage();
}
public String getFieldNameLanguage(String name) {
return name + "_" + mCore.getCurrentLanguage();
}
/**
* Inicia una transaccion
* @param void
* @return void.
*/
public void startTransaction()
{
mCore.getDB().beginTransaction();
}
/**
* Finaliza una transaccion
* @param void
* @return void.
*/
public void endTransaction()
{
mCore.getDB().endTransaction();
}
/**
* Indica si estamos en una transaccion
* @param void
* @return Boolean True si hay una transaccion en curso, false en caso contrario.
*/
public boolean inTransaction()
{
return mCore.getDB().inTransaction();
}
/**
* Confirma la ejecucion correcta de una transaccion
* @param void
* @return void.
*/
public void successfulTransaction()
{
mCore.getDB().setTransactionSuccessful();
}
}

View File

@ -1,694 +0,0 @@
/*
* Copyright (C) 2008 Javier Perez Pacheco y Javier Ros Moreno
*
* Android Data Framework: Trabajo con BD SQLite en Android
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Javier Perez Pacheco
* Cadiz (Spain)
* javi.pacheco@gmail.com
*
* Javier Ros Moreno
* jros@jros.org
*
*
*/
package com.android.dataframework;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import com.android.dataframework.core.Field;
import com.android.dataframework.core.Table;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map.Entry;
public class Entity {
private String mTable;
private long mId = -1;
private long mForceId = -1;
protected HashMap<String, Object> mAttributes = new HashMap<>();
protected HashMap<String, Object> mMultilanguagesAttributes = new HashMap<>();
/**
* Devuelve el siguiente _id
*
* @return siguiente _id
*/
public long nextId() {
if (mForceId<0)
{
Cursor c = DataFramework.getInstance().getCursor(mTable, new String[]{DataFramework.KEY_ID},
null, null, null, null, DataFramework.KEY_ID + " desc", "1");
if (!c.moveToFirst()) {
c.close();
return 1;
} else {
long Id = c.getLong(0) + 1;
c.close();
return Id;
}
} else {
return mForceId;
}
}
/**
* Devuelve el _id del registro
*
* @return id del registro
*/
public long getId() {
return mId;
}
/**
* Devuelve la tabla de la entidad
*
* @return tabla de la entidad
*/
public String getTable() {
return mTable;
}
/**
* Devuelve si es una actualizacion del registro
*
* @return true si es una actualizacion
*/
public boolean isUpdate() {
return mId >= 0;
}
/**
* Devuelve si es un nuevo de registro
*
* @return true si es una nuevo registro
*/
public boolean isInsert() {
return (mId < 0);
}
/**
* Devuelve el valor a un atributo en tipo entero
*
* @param name nombre del campo
* @return valor del campo (Tipo int)
*/
public Integer getInt(String name)
{
Object obj = getValue(name);
if (obj == null){
return 0;
}else{
return Integer.parseInt(obj.toString());
}
}
/**
* Devuelve el valor a un atributo en tipo String
*
* @param name nombre del campo
* @return valor del campo (Tipo String)
*/
public String getString(String name)
{
Field f = getTableObject().getField(name);
if (f.getType().equals("string-identifier")) {
return DataFramework.getInstance().getStringFromIdentifier(getValue(name).toString());
} else {
Object obj = getValue(name);
if (obj == null){
return "";
}else{
return obj.toString();
}
}
}
/**
* Devuelve el idenfificador del recurso en la aplicacion
*
* @param name nombre del campo
* @return valor (Tipo int)
*/
public int getDrawableIdentifier(String name)
{
return DataFramework.getInstance().getContext().getResources().getIdentifier(DataFramework.getInstance().getPackage() + ":drawable/"+getValue(name).toString(), null, null);
}
/**
* Devuelve un bitmap del recurso en la aplicacion
*
* @param name nombre del campo
* @return valor (Tipo bitmap)
*/
public Bitmap getBitmap(String name)
{
int id = DataFramework.getInstance().getContext().getResources().getIdentifier(DataFramework.getInstance().getPackage() + ":drawable/"+getValue(name).toString(), null, null);
java.io.InputStream is = DataFramework.getInstance().getContext().getResources().openRawResource(id);
BitmapDrawable bmd = new BitmapDrawable(BitmapFactory.decodeStream(is));
return bmd.getBitmap();
}
/**
* Devuelve un BitmapDrawable del recurso en la aplicacion
*
* @param name nombre del campo
* @return valor (Tipo BitmapDrawable)
*/
public BitmapDrawable getBitmapDrawable(String name)
{
int id = DataFramework.getInstance().getContext().getResources().getIdentifier(DataFramework.getInstance().getPackage() + ":drawable/"+getValue(name).toString(), null, null);
java.io.InputStream is = DataFramework.getInstance().getContext().getResources().openRawResource(id);
return new BitmapDrawable(BitmapFactory.decodeStream(is));
}
/**
* Devuelve un objeto Drawable del recurso en la aplicaci<EFBFBD>n
*
* @param name nombre del campo
* @return valor (Tipo Drawable)
*/
public Drawable getDrawable(String name)
{
int id = DataFramework.getInstance().getContext().getResources().getIdentifier(DataFramework.getInstance().getPackage() + ":drawable/"+getValue(name).toString(), null, null);
return DataFramework.getInstance().getContext().getResources().getDrawable(id);
}
/**
* Devuelve el Cursor de la entidad con un solo campo pasado como par<EFBFBD>metro.
* Si la entidad es un nuevo registro devuelve null
*
* @param field campo (Objeto Field)
* @return cursor
*/
public Cursor getCursor(String field) {
try {
if (isInsert()){
return null;
}
String fieldName = field;
Field f = DataFramework.getInstance().getTable(mTable).getField(fieldName);
if (f.getType().equals("multilanguage")){
fieldName += "_" + DataFramework.getInstance().getCurrentLanguage();
}
Cursor mCursor = DataFramework.getInstance().getDB().query(true, mTable, new String[] {fieldName}, DataFramework.KEY_ID + "=" + mId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return null;
}
/**
* Devuelve el Cursor de la entidad con todos los campos de esta.
* Si la entidad es un nuevo registro devuelve null
*
* @return cursor
*/
public Cursor getCursor() {
try {
if (isInsert()){
return null;
}
Cursor mCursor = DataFramework.getInstance().getDB().query(true, mTable, DataFramework.getInstance().getTable(mTable).getFieldsToArray(), DataFramework.KEY_ID + "=" + mId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return null;
}
/**
* Devuelve un string de la entidad. Formato obtenido del archivo XML
*
* @return string
*/
@Override
public String toString()
{
String[] arString = DataFramework.getInstance().getTable(mTable).getToString().split("%");
String out = "";
for (String anArString : arString) {
if (isAttribute(anArString)) {
Field f = getTableObject().getField(anArString);
if (f.getType().equals("foreign-key")) {
out += getEntity(anArString).toString();
} else {
out += getString(anArString);
}
} else if (anArString.equals(DataFramework.KEY_ID)) {
out += mId;
} else {
out += anArString;
}
}
return out;
}
/**
* Devuelve el _id que queremos forzar al guardar la entidad
*
* @return id a forzar
*/
public long getForceId() {
return mForceId;
}
/**
* Establece el _id que queremos forzar al guardar la entidad
*
* @param forceId identificador
*/
public void setForceId(long forceId) {
this.mForceId = forceId;
}
public Table getTableObject()
{
return DataFramework.getInstance().getTable(mTable);
}
/**
* Devuelve el valor a un atributo en tipo entero largo
*
* @param name nombre del campo
* @return valor del campo (Tipo int)
*/
public long getLong(String name)
{
Object obj = getValue(name);
if (obj == null){
return 0;
}else{
return Long.parseLong(obj.toString());
}
}
public double getDouble(String name)
{
Object obj = getValue(name);
return obj == null? 0.0 : Double.parseDouble(obj.toString());
}
public float getFloat(String name)
{
Object obj = getValue(name);
return obj == null? 0.0f : Float.parseFloat(obj.toString());
}
/**
* A<EFBFBD>ade los atributos desde el objeto table.
* Se llama desde el constructor.
*/
private void addAllAttributesFromTable()
{
Table t = getTableObject();
for (int i=0; i<t.getFields().size(); i++)
{
Field f = t.getFields().get(i);
mAttributes.put(f.getName(), null);
}
}
/**
* Carga los valores creando un cursor.l
*/
protected void loadData()
{
Cursor c = getCursor();
if (c!=null) {
loadData(c);
c.close();
}
}
/**
* Carga los valores de cualquier cursor.
*
* @param c Cursor al registro con los datos.
*/
protected void loadData(Cursor c)
{
if (c!=null) {
HashMap<String, Object> attribs = mAttributes; // Para reducir el acceso al heap.
Object[] attributeNames = attribs.keySet().toArray();
int attributeCount = attributeNames.length;
for (Object attributeName1 : attributeNames) {
String attributeName = attributeName1.toString();
Field f = getTableObject().getField(attributeName);
int indexField;
if (f.getType().equals("multilanguage")) {
indexField = c.getColumnIndexOrThrow(attributeName + "_" + DataFramework.getInstance().getCurrentLanguage());
} else {
indexField = c.getColumnIndexOrThrow(attributeName);
}
switch (f.getType()) {
case "text":
case "multilanguage":
case "string-identifier":
case "drawable-identifier":
attribs.put(attributeName, c.getString(indexField));
break;
case "int":
attribs.put(attributeName, c.getLong(indexField));
break;
case "foreign-key":
attribs.put(attributeName, c.getLong(indexField));
break;
case "real":
attribs.put(attributeName, c.getDouble(indexField));
break;
default:
attribs.put(attributeName, c.getString(indexField));
break;
}
}
}
}
/**
* Constructor a partir de un cursor, de esta forma nos ahorramos el acceso a la base de datos.
*
* @param table Nombre de la tabla
* @param c Cursor al registro a cargar.
*/
public Entity(String table, Cursor c)
{
mId = c.getLong(c.getColumnIndexOrThrow(DataFramework.KEY_ID));
this.mTable = table;
mForceId = -1;
addAllAttributesFromTable();
loadData(c);
}
/**
* Constructor - toma como valor el nombre de tabla de la entidad. Solo para nuevos registros
*
* @param table la tabla de la entidad
*/
public Entity (String table) {
this.mTable = table;
mForceId = -1;
addAllAttributesFromTable();
}
/**
* Constructor - toma como valor el nombre de tabla de la entidad y un identificador.
* Solo para actualizaciones de registros
*
* @param table la tabla de la entidad
* @param id el identificador de la entidad
*/
public Entity (String table, Long id) {
this.mTable = table;
mForceId = -1;
if (id > 0){
this.mId = id;
}
addAllAttributesFromTable();
loadData();
}
/**
* Constructor - toma como valor el nombre de tabla de la entidad y un XML con la serializaci<EFBFBD>n de la entidad.
*
* @param table la tabla de la entidad
* @param xml Xml devuelto por getSerialization o getXml
*/
public Entity (String table, String xml) {
this.mTable = table;
mForceId = -1;
addAllAttributesFromTable();
loadFromXml(xml);
}
/**
* Estable el valor a un atributo
*
* @param name nombre del campo
* @param value valor del campo
*/
public void setValue(String name, Object value)
{
if (Entity.class.isInstance(value)){
mAttributes.put(name, ((Entity)value).getId());
}else{
mAttributes.put(name, value);
}
}
/**
* Estable el valor a un atributo multilenguaje
*
* @param name nombre del campo
* @param value valor del campo
*/
public void setMultilanguageValue(String name, String lang, Object value)
{
mMultilanguagesAttributes.put(name + "_" + lang, value);
}
/**
* Devuelve el valor a un atributo
*
* @param name nombre del campo
* @return valor del campo (Tipo Object)
*/
public Object getValue(String name)
{
return mAttributes.get(name);
}
/**
* Devuelve el valor a un atributo en tipo Entity. Para claves foraneas.
* Creamos el objeto a partir del ID almacenado en el campo.
*
* @param name nombre del campo
* @return valor del campo (Tipo Entity)
*/
public Entity getEntity(String name)
{
Field f = getTableObject().getField(name);
if (f != null && f.getType().equals("foreign-key")){
return new Entity(f.getForeignTable(), getLong(name));
}else{
return null;
}
}
/**
* Comprueba si el campo pasado por par<EFBFBD>metro es un atributo de la entidad
*
* @param name nombre del campo
* @return true si es un campo
*/
public boolean isAttribute(String name) {
try {
return getTableObject().getField(name) != null;
} catch (NullPointerException e) {
return false;
}
}
/**
* Indica si un atributo es nulo
* @param name
* @return si o no.
*/
public boolean isNull(String name)
{
return mAttributes.get(name) == null;
}
/**
* Guarda una fila en la base de datos. Si _id es -1 es un nuevo registro, otra cosa una actualizacion
*
* @return id or -1 if failed
*/
public boolean save() {
try {
ContentValues args = new ContentValues();
if (isInsert()) {
args.put(DataFramework.KEY_ID, "" + nextId());
} else {
if (mForceId>0) {
args.put(DataFramework.KEY_ID, "" + mForceId);
}
}
for (int i=0; i < getTableObject().getFields().size(); i++)
{
Field f = getTableObject().getFields().get(i);
String attr = f.getName();
Object value = getValue(attr);
if (value != null)
{
// TODO: Verificar si no hay que usar las distintas llamdas
// al metodo ContentValues.put() dependiendo del tipo del
// campo.
//
// Lo que est<EFBFBD> muy claro es que nunca se guarda null para ning<EFBFBD>n
// campo.
if (f.getType().equals("multilanguage")) {
args.put(f.getName() + "_" + DataFramework.getInstance().getCurrentLanguage(), value.toString());
} else {
args.put(f.getName(), value.toString());
}
}
}
for (Entry<String, Object> e : mMultilanguagesAttributes.entrySet()) {
args.put(e.getKey(), e.getValue().toString());
}
if (isInsert()) {
mId = DataFramework.getInstance().getDB().insert(mTable, null, args);
return (mId > 0);
}else{
return DataFramework.getInstance().getDB().update(mTable, args, DataFramework.KEY_ID + "=" + mId, null) > 0;
}
} catch (SQLException e) {
Log.e("Exception on query", e.toString());
}
return false;
}
/**
* Borra una fila
*
* @return "true" si es borrada, "false" otra cosa
*/
public boolean delete() {
boolean res = DataFramework.getInstance().getDB().delete(mTable, DataFramework.KEY_ID + "=" + mId, null) > 0;
mId = -1;
return res;
}
/**
* Devuelve la serializaci<EFBFBD>n de la entidad en formato de cadena. (XML)
* @return XML
*/
public String getSerialization()
{
return getXml();
}
/**
* Devuelve un XML con los valores de la entidad.
* @return
*/
private String getXml()
{
HashMap<String, Object> attribs = mAttributes; // Para reducir el acceso al heap.
Object[] attributeNames = attribs.keySet().toArray();
int attributeCount = attributeNames.length;
String result = "<entity>\n";
result += "<attribute name=\"_id\" value=\"" + mId + "\"/>\n";
for (Object attributeName : attributeNames) {
if (!isNull(attributeName.toString())) {
result += "<attribute name=\"" + attributeName.toString() + "\"" +
" value=\"" + getValue(attributeName.toString()).toString() + "\"/>\n";
}
}
result += "</entity>\n";
return result;
}
/**
* Carga los valores de la entidad desde un XML creado desde getXML.
* @param xml
*/
public void loadFromXml(String xml)
{
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser x = factory.newPullParser();
x.setInput(new StringReader(xml));
int eventType = x.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT)
{
if (eventType == XmlPullParser.START_TAG) {
if (x.getName().equals("attribute")) {
String name = x.getAttributeValue(null, "name");
if (name != null) {
String value = x.getAttributeValue(null, "value");
if (name.equals("_id")){
mId = Long.parseLong(value);
}else{
setValue(name, value);
}
}
}
}
eventType = x.next();
}
} catch (XmlPullParserException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@ -1,494 +0,0 @@
/**
*
* Copyright (C) 2008 Javier Perez Pacheco y Javier Ros Moreno
*
* Android Data Framework: Trabajo con BD SQLite en Android
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Javier Perez Pacheco
* Cadiz (Spain)
* javi.pacheco@gmail.com
*
* Javier Ros Moreno
* jros@jros.org
*
*
* EntityCursor es una clase que permite el acceso a una coleccion de entidades
* sin necesidad de tener que crear un objeto Entity por cada registro cargado
* en el cursor.
*
* Ademas tambien implementa la interface Iterable, con lo que podemos usar el cursor
* en una instruccion foreach.
*
* Ejemplo de uso:
*
* for (Entity entity: myEntityCursor)
* {
* if (entity.getString("name").equals("Javier"))
* giveAGreatPresent(entity);
* }
*
*/
package com.android.dataframework;
import android.content.ContentResolver;
import android.database.CharArrayBuffer;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Bundle;
import java.util.Iterator;
/**
* @author javier
*
*/
public class EntityCursor implements Cursor, Iterable<Entity> {
private Cursor mCursor;
private String mTableName;
private Entity mCurrentEntity;
public EntityCursor(String tableName, Cursor c)
{
mTableName = tableName;
mCursor = c;
c.moveToFirst();
}
/**
* Cuando se efect<EFBFBD>a un movimiento en el cursor actualizamos la entidad en curso.
*
* @param oldPosition
* @param newPosition
*/
private void onMove(int oldPosition, int newPosition)
{
if (oldPosition != newPosition || mCurrentEntity == null){
mCurrentEntity = new Entity(mTableName, mCursor);
}
}
/**
* Devuelve la entidad en curso.
*
* @return
*/
public Entity getEntity()
{
return mCurrentEntity;
}
/**
* Implementaci<EFBFBD>n de los m<EFBFBD>todos abstractos de la clase Cursor.
*
* Tan solo realizamos las acciones indicadas sobre el Cursor pasado
* en el constructor.
*/
/* (non-Javadoc)
* @see android.database.Cursor#close()
*/
@Override
public void close() {
mCursor.close();
}
/* (non-Javadoc)
* @see android.database.Cursor#copyStringToBuffer(int, android.database.CharArrayBuffer)
*/
@Override
public void copyStringToBuffer(int columnIndex, CharArrayBuffer buffer) {
mCursor.copyStringToBuffer(columnIndex, buffer);
}
/* (non-Javadoc)
* @see android.database.Cursor#deactivate()
*/
@Override
public void deactivate() {
mCursor.deactivate();
}
/* (non-Javadoc)
* @see android.database.Cursor#getBlob(int)
*/
@Override
public byte[] getBlob(int columnIndex) {
return mCursor.getBlob(columnIndex);
}
/* (non-Javadoc)
* @see android.database.Cursor#getColumnCount()
*/
@Override
public int getColumnCount() {
return mCursor.getColumnCount();
}
/* (non-Javadoc)
* @see android.database.Cursor#getColumnIndex(java.lang.String)
*/
@Override
public int getColumnIndex(String columnName) {
return mCursor.getColumnIndex(columnName);
}
/* (non-Javadoc)
* @see android.database.Cursor#getColumnIndexOrThrow(java.lang.String)
*/
@Override
public int getColumnIndexOrThrow(String columnName)
throws IllegalArgumentException {
return mCursor.getColumnIndexOrThrow(columnName);
}
/* (non-Javadoc)
* @see android.database.Cursor#getColumnName(int)
*/
@Override
public String getColumnName(int columnIndex) {
return mCursor.getColumnName(columnIndex);
}
/* (non-Javadoc)
* @see android.database.Cursor#getColumnNames()
*/
@Override
public String[] getColumnNames() {
return mCursor.getColumnNames();
}
/* (non-Javadoc)
* @see android.database.Cursor#getCount()
*/
@Override
public int getCount() {
return mCursor.getCount();
}
/* (non-Javadoc)
* @see android.database.Cursor#getDouble(int)
*/
@Override
public double getDouble(int columnIndex) {
return mCursor.getDouble(columnIndex);
}
/* (non-Javadoc)
* @see android.database.Cursor#getExtras()
*/
@Override
public Bundle getExtras() {
return mCursor.getExtras();
}
/* (non-Javadoc)
* @see android.database.Cursor#getFloat(int)
*/
@Override
public float getFloat(int columnIndex) {
return mCursor.getFloat(columnIndex);
}
/* (non-Javadoc)
* @see android.database.Cursor#getInt(int)
*/
@Override
public int getInt(int columnIndex) {
return mCursor.getInt(columnIndex);
}
/* (non-Javadoc)
* @see android.database.Cursor#getLong(int)
*/
@Override
public long getLong(int columnIndex) {
return mCursor.getLong(columnIndex);
}
/* (non-Javadoc)
* @see android.database.Cursor#getPosition()
*/
@Override
public int getPosition() {
return mCursor.getPosition();
}
/* (non-Javadoc)
* @see android.database.Cursor#getShort(int)
*/
@Override
public short getShort(int columnIndex) {
return mCursor.getShort(columnIndex);
}
/* (non-Javadoc)
* @see android.database.Cursor#getString(int)
*/
@Override
public String getString(int columnIndex) {
return mCursor.getString(columnIndex);
}
/* (non-Javadoc)
* @see android.database.Cursor#getWantsAllOnMoveCalls()
*/
@Override
public boolean getWantsAllOnMoveCalls() {
return mCursor.getWantsAllOnMoveCalls();
}
/* (non-Javadoc)
* @see android.database.Cursor#setExtras()
*/
@Override
public void setExtras(Bundle extras) { mCursor.setExtras(extras); }
/* (non-Javadoc)
* @see android.database.Cursor#isAfterLast()
*/
@Override
public boolean isAfterLast() {
return mCursor.isAfterLast();
}
/* (non-Javadoc)
* @see android.database.Cursor#isBeforeFirst()
*/
@Override
public boolean isBeforeFirst() {
return mCursor.isBeforeFirst();
}
/* (non-Javadoc)
* @see android.database.Cursor#isClosed()
*/
@Override
public boolean isClosed() {
return mCursor.isClosed();
}
/* (non-Javadoc)
* @see android.database.Cursor#isFirst()
*/
@Override
public boolean isFirst() {
return mCursor.isFirst();
}
/* (non-Javadoc)
* @see android.database.Cursor#isLast()
*/
@Override
public boolean isLast() {
return mCursor.isLast();
}
/* (non-Javadoc)
* @see android.database.Cursor#isNull(int)
*/
@Override
public boolean isNull(int columnIndex) {
return mCursor.isNull(columnIndex);
}
/* (non-Javadoc)
* @see android.database.Cursor#move(int)
*/
@Override
public boolean move(int offset) {
int oldPos = getPosition();
boolean result = mCursor.move(offset);
int newPos = getPosition();
onMove(oldPos, newPos);
return result;
}
/* (non-Javadoc)
* @see android.database.Cursor#moveToFirst()
*/
@Override
public boolean moveToFirst() {
int oldPos = getPosition();
boolean result = mCursor.moveToFirst();
int newPos = getPosition();
onMove(oldPos, newPos);
return result;
}
/* (non-Javadoc)
* @see android.database.Cursor#moveToLast()
*/
@Override
public boolean moveToLast() {
int oldPos = getPosition();
boolean result = mCursor.moveToLast();
int newPos = getPosition();
onMove(oldPos, newPos);
return result;
}
/* (non-Javadoc)
* @see android.database.Cursor#moveToNext()
*/
@Override
public boolean moveToNext() {
int oldPos = getPosition();
boolean result = mCursor.moveToNext();
int newPos = getPosition();
onMove(oldPos, newPos);
return result;
}
/* (non-Javadoc)
* @see android.database.Cursor#moveToPosition(int)
*/
@Override
public boolean moveToPosition(int position) {
int oldPos = getPosition();
boolean result = mCursor.moveToPosition(position);
int newPos = getPosition();
onMove(oldPos, newPos);
return result;
}
/* (non-Javadoc)
* @see android.database.Cursor#moveToPrevious()
*/
@Override
public boolean moveToPrevious() {
int oldPos = getPosition();
boolean result = mCursor.moveToPrevious();
int newPos = getPosition();
onMove(oldPos, newPos);
return result;
}
/* (non-Javadoc)
* @see android.database.Cursor#registerContentObserver(android.database.ContentObserver)
*/
@Override
public void registerContentObserver(ContentObserver observer) {
mCursor.registerContentObserver(observer);
}
/* (non-Javadoc)
* @see android.database.Cursor#registerDataSetObserver(android.database.DataSetObserver)
*/
@Override
public void registerDataSetObserver(DataSetObserver observer) {
mCursor.registerDataSetObserver(observer);
}
/* (non-Javadoc)
* @see android.database.Cursor#requery()
*/
@Override
public boolean requery() {
return mCursor.requery();
}
/* (non-Javadoc)
* @see android.database.Cursor#respond(android.os.Bundle)
*/
@Override
public Bundle respond(Bundle extras) {
return mCursor.respond(extras);
}
/* (non-Javadoc)
* @see android.database.Cursor#setNotificationUri(android.content.ContentResolver, android.net.Uri)
*/
@Override
public void setNotificationUri(ContentResolver cr, Uri uri) {
mCursor.setNotificationUri(cr, uri);
}
/* (non-Javadoc)
* @see android.database.Cursor#unregisterContentObserver(android.database.ContentObserver)
*/
@Override
public void unregisterContentObserver(ContentObserver observer) {
mCursor.unregisterContentObserver(observer);
}
/* (non-Javadoc)
* @see android.database.Cursor#unregisterDataSetObserver(android.database.DataSetObserver)
*/
@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
mCursor.unregisterDataSetObserver(observer);
}
/**
* Implementaci<EFBFBD>n de los m<EFBFBD>todos de la Interface Iterable.
*
* Tan solo realizamos las acciones indicadas sobre el Cursor pasado
* en el constructor.
*/
@Override
public Iterator<Entity> iterator() {
return new EntityIterator();
}
/**
* Definicion e implementacion de la clase EntityIterator
*/
public class EntityIterator implements Iterator<Entity> {
@Override
public boolean hasNext()
{
return !(mCursor.isLast() || mCursor.isAfterLast());
}
@Override
public Entity next()
{
if (mCurrentEntity == null){
moveToFirst();
}else{
moveToNext();
}
return mCurrentEntity;
}
@Override
public void remove()
{
}
}
public int getType(int columnIndex) {
return 0;
}
@Override
public Uri getNotificationUri() {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -1,191 +0,0 @@
package com.android.dataframework;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.android.dataframework.core.Field;
import com.android.dataframework.core.Table;
import java.util.HashMap;
import java.util.Map;
public abstract class EntityEditActivity extends Activity
{
public final static String TABLENAME_ID = "tablename";
protected Long mRowId;
protected String mKeyField;
protected Bundle mySavedInstanceState;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mKeyField = getKeyFieldName();
mySavedInstanceState = savedInstanceState;
setView();
}
/**
* Guarda el nombre del campo clave
*/
protected String getKeyFieldName()
{
return DataFramework.KEY_ID;
}
abstract protected String getTableName();
/**
* Asignar vista
*/
abstract protected void setView();
@Override
protected void onPause() {
super.onPause();
closeDatabase();
}
/**
* Cerrar la base de datos.
*/
protected void closeDatabase()
{
DataFramework.getInstance().close();
}
@Override
protected void onResume() {
super.onResume();
// Abrimos la base de datos
openDatabase();
// Cargamos los datos
loadDataToView();
}
/**
* Cerrar la base de datos.
*/
abstract protected void openDatabase();
protected void loadDataToView()
{
// Actuamos dependiendo si hay datos guardados en el estado de la instancia.
if (mySavedInstanceState == null)
{
// Si no hay datos guardados es que se trata de la primera vez,
// asi que vemos si hay identificador de fila, si la hay es que es una edicion
// si no es que es un alta nueva.
Bundle extras = getIntent().getExtras();
mRowId = (Long) (extras != null ? extras.get(mKeyField)
: null);
if (mRowId != null)
{
// Si hay RowId cargamos de la base de datos el registro en cuestion
loadDataFromEntityToView(new Entity(getTableName(), mRowId));
}
else
{
// Si no hay RowId se trata de un nuevo alta
blankView();
}
}
else
{
// Si hay estado guardado hay que restaurar los datos desde el estado
// de la actividad.
loadDataFromState(mySavedInstanceState);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Almacenamos el estado
mySavedInstanceState = outState;
// Si hay RowId lo guardamos en el estado.
if (mRowId != null)
outState.putLong(mKeyField, mRowId);
// Guardamos el resto de datos en el estado
saveDataToState(mySavedInstanceState);
}
abstract protected int getMainViewId();
protected Map<String, View> getAttributeViews()
{
Map<String, View> views = new HashMap<>();
View mainView = findViewById(getMainViewId());
Table table = new Table(getTableName());
// Buscamos los Views que tengan en el Tag el nombre de uno de los campos.
for (Field f: table.getFields())
{
View v = mainView.findViewWithTag(f.getName());
if (v != null)
views.put(f.getName(), v);
}
return views;
}
/**
* Carga los datos de la base de datos a la interfaz de usuario.
* Prepara la vista para editar los datos.
* @param rowId Identificador unico del registro.
*/
protected void loadDataFromEntityToView(Entity entity)
{
Table table = new Table(getTableName());
Map<String, View> views = getAttributeViews();
// Buscamos los Views que tengan en el Tag el nombre de uno de los campos.
for (Field f: table.getFields())
{
Object value = entity.getValue(f.getName());
View view = views.get(f.getName());
if (value != null && view != null)
{
if (EditText.class.isInstance(view))
{
((EditText)view).setText(value.toString());
}
}
}
}
/**
* Guardar datos en la base de datos, se debe llamar desde el
* boton guardar, no se llama automaticamente.
*/
abstract protected void saveToDB();
/**
* Carga los datos del estado de la actividad a la interfaz de usuario
* Restaura los valores previamente guardados en el estado de la actividad.
* @param state Estado de donde sacar los datos
*/
abstract protected void loadDataFromState(Bundle state);
/**
* Guarda los datos de la interface en el estado para
* ser restaurados despues.
* @param outState
*/
abstract protected void saveDataToState(Bundle state);
/**
* Prepara la interfaz de usuario para crear un nuevo registro.
*/
abstract protected void blankView();
}

View File

@ -1,504 +0,0 @@
/*
* Copyright (C) 2008 Javier Perez Pacheco y Javier Ros Moreno
*
* Android Data Framework: Trabajo con BD SQLite en Android
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Javier Perez Pacheco
* Cadiz (Spain)
* javi.pacheco@gmail.com
*
* Javier Ros Moreno
* jros@jros.org
*
*
*/
package com.android.dataframework.core;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.android.dataframework.DataFramework;
import com.android.dataframework.Entity;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
public class DataFrameworkCore {
private final static int TYPESQL_INSERT = 0;
private final static int TYPESQL_UPDATE = 1;
private final static int TYPESQL_DELETE = 2;
private String mPackage = "";
private ArrayList<String> mLanguages = new ArrayList<>();
private String mCurrentLanguage;
private SQLiteDatabase mDb;
private DatabaseHelper mDbHelper;
private ArrayList<Table> mTables;
private String mDataBaseName = "";
private int mDataBaseOldVersion = 0;
private int mDataBaseVersion = 0;
private Context mCtx;
private boolean mSaveInitialValues = false;
/**
* Constructor
*/
public DataFrameworkCore()
{
}
private class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper() {
super(mCtx, mDataBaseName, null, mDataBaseVersion);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
System.out.println("(onCreate) CREATE TABLES");
mDataBaseOldVersion = 0;
ArrayList<Table> tables = mTables;
int tableCount = tables.size();
for (int i = 0; i < tableCount; i++)
db.execSQL(tables.get(i).getSQLCreateTable());
mSaveInitialValues = true;
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w("TableDB", "Upgrading database from version " + oldVersion + " to " + newVersion);
mDataBaseOldVersion = oldVersion;
ArrayList<Table> tables = mTables;
int tableCount = tables.size();
for (int i = 0; i < tableCount; i++)
{
Table t = tables.get(i);
if (add(t.getNewInVersion(), oldVersion, newVersion))
{
System.out.println("(onUpgrade) CREATE TABLE: " + t.getName());
db.execSQL(t.getSQLCreateTable());
} else
{
ArrayList<Field> fields = t.getFields();
int fieldCount = fields.size();
for (int j=0; j < fieldCount; j++) {
Field f = fields.get(j);
if (add(f.getNewInVersion(), oldVersion, newVersion)) {
String sql = t.getSQLAddField(f);
if (sql!=null) {
System.out.println("(onUpgrade) ADD FIELD: " + t.getName() + "(" + f.getName() + ")");
db.execSQL(sql);
}
}
}
}
}
mSaveInitialValues = true;
}
private boolean add(int version, int oldVersion, int newVersion) {
return version > oldVersion && version <= newVersion;
}
}
/**
* Abre una conexion a ADF generando todos los objetos a partir de los archivos XML
* pasados como parametros
*
* @param context Actividad principal
* @param idTables recurso XML con las tablas
* @param idInitialValues recurso XML con los registros a generar en la primera carga
*
*/
public void open(Context context, String namePackage, ArrayList<Table> tables) throws XmlPullParserException, IOException {
try {
// Solo en el caso de que no est<EFBFBD>n cargadas las tablas, leemos el XML
if (tables.size() == 0)
{
mPackage = namePackage;
mTables = tables;
mCtx = context;
int idTables = context.getResources().getIdentifier(namePackage+":xml/tables", null, null);
if (idTables!=0) {
XmlResourceParser x = mCtx.getResources().getXml(idTables);
int eventType = x.getEventType();
Table currentTable = new Table( "" );
Field currentField = new Field( "" );
while (eventType != XmlPullParser.END_DOCUMENT) {
if ( eventType == XmlPullParser.START_TAG ) {
if (x.getName().equals("database")) {
mDataBaseName = x.getAttributeValue(null, "name");
mDataBaseVersion = Integer.parseInt(x.getAttributeValue(null, "version"));
if (x.getAttributeValue(null, "languages")!=null) {
boolean isFirst = true;
StringTokenizer tokens = new StringTokenizer(x.getAttributeValue(null, "languages"), "|");
while(tokens.hasMoreTokens()){
String token = tokens.nextToken();
mLanguages.add(token);
if (isFirst) { mCurrentLanguage = token; isFirst = false; }
if (Locale.getDefault().getLanguage().equals(token)) mCurrentLanguage = token;
}
System.out.println("Lenguaje por defecto usado en la base de datos: " + mCurrentLanguage);
}
} else if (x.getName().equals("table")) {
currentTable = new Table( x.getAttributeValue(null, "name") );
if (x.getAttributeValue(null, "to-string")!=null) currentTable.setToString(x.getAttributeValue(null, "to-string"));
if (x.getAttributeValue(null, "backup")!=null) {
if (x.getAttributeValue(null, "backup").equals("no")) currentTable.setBackup(false);
}
if ( x.getAttributeValue(null, "new-in-version") != null ) {
currentTable.setNewInVersion(Integer.parseInt( x.getAttributeValue(null, "new-in-version") ));
}
} else if (x.getName().equals("field")) {
currentField = new Field ( x.getAttributeValue(null, "name") );
if ( x.getAttributeValue(null, "type") != null ) currentField.setType( x.getAttributeValue(null, "type") );
if ( x.getAttributeValue(null, "foreign-table") != null ) currentField.setForeignTable( x.getAttributeValue(null, "foreign-table") );
if ( x.getAttributeValue(null, "obligatory") != null ) {
if (x.getAttributeValue(null, "obligatory")=="true") currentField.setObligatory( true );
}
if ( x.getAttributeValue(null, "size") != null ) currentField.setSize( Integer.parseInt( x.getAttributeValue(null, "size") ) );
if ( x.getAttributeValue(null, "default") != null ) currentField.setTextDefault( x.getAttributeValue(null, "default") );
if ( x.getAttributeValue(null, "new-in-version") != null ) {
currentField.setNewInVersion(Integer.parseInt( x.getAttributeValue(null, "new-in-version") ));
}
currentTable.addField(currentField);
}
}
if ( eventType == XmlPullParser.END_TAG ) {
if (x.getName().equals("table")) {
tables.add(currentTable);
}
}
eventType = x.next();
}
x.close();
} else {
System.out.println("=========================================");
System.out.println("No se ha encontrado el archivo tables.xml");
System.out.println("=========================================");
}
}
// Presuponemos que no se guardan los valores iniciales.
mSaveInitialValues = false;
mDbHelper = new DatabaseHelper();
mDb = mDbHelper.getWritableDatabase();
if (mSaveInitialValues)
saveInitialValues();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Cierra la conexion a la base de datos
*
*/
public void close() {
mDbHelper.close();
}
/**
* Genera los valores iniciales de la primera carga en el caso que se haya especificado archivo
*
*/
public void saveInitialValues() throws XmlPullParserException, IOException {
try {
for (int i=mDataBaseOldVersion+1; i<=mDataBaseVersion; i++) {
int idInitialValues = mCtx.getResources().getIdentifier(mPackage+":xml/initialvalues_v"+i, null, null);
if (idInitialValues!=0) {
XmlResourceParser x = mCtx.getResources().getXml(idInitialValues);
insertXML(x);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Crea una copia de seguridad de la base de datos
*
* @param file Archivo XML donde hace la copia
*
*/
public void backup(String file) throws XmlPullParserException, IOException {
backup(file, false);
}
/**
* Crea una copia de seguridad de la base de datos
*
* @param file Archivo XML donde hace la copia
* @param forceBackup Forzar a hacer backup aunque la table no lo permita
*
*/
public void backup(String file, boolean forceBackup) throws XmlPullParserException, IOException {
File f = new File(file);
if (f.exists()) f.delete();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<values>\n");
List<Table> tables = mTables;
int tableCount = tables.size();
System.out.println("tablas: "+ tables.size());
for (int i = 0; i < tableCount; i++)
{
Table t = tables.get(i);
if (t.isBackup() || forceBackup) {
String tableName = t.getName();
System.out.println("tabla: "+ tableName);
String[] aux = t.getFieldsToArray();
Cursor c = mDb.query(tableName, aux, null, null, null, null, null);
c.moveToFirst();
ArrayList<Field> fields = t.getFields();
int fieldCount = fields.size();
while (!c.isAfterLast()) {
osw.append("<row table=\"").append(tableName).append("\" id=\"").append(c.getString(c.getColumnIndex(DataFramework.KEY_ID))).append("\">\n");
for (int j = 0; j < fieldCount; j++)
{
Field field = fields.get(j);
if (c.getString(c.getColumnIndex(field.getName()))!=null)
osw.append("<field name=\"").append(field.getName()).append("\" value=\"").append(c.getString(c.getColumnIndex(field.getName())).replace("\"", "&quot;")).append("\" />\n");
}
osw.append("</row>\n");
c.moveToNext();
}
c.close();
}
}
osw.append("</values>\n");
osw.flush();
osw.close();
}
/**
* Reestablece una copia de seguridad de la base de datos
*
* @param file Archivo XML donde esta la copia
*
*/
public void restore(String file) throws XmlPullParserException, IOException {
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser x = factory.newPullParser();
x.setInput(new FileReader(file));
insertXML(x);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Inserta los registros de un XmlResourceParser en la Base de datos
*
* @param x Archivo XmlResourceParser
*
*/
private void insertXML(XmlPullParser x) throws XmlPullParserException, IOException {
try {
int eventType = x.getEventType();
Entity currenEntity = null;
int typesql = TYPESQL_INSERT;
while (eventType != XmlPullParser.END_DOCUMENT) {
if ( eventType == XmlPullParser.START_TAG ) {
if (x.getName().equals("row")) {
currenEntity = null;
if ( x.getAttributeValue(null, "table") != null ) {
long id = -1;
if ( x.getAttributeValue(null, "action") != null ) {
if (x.getAttributeValue(null, "action").equals("update")) {
typesql = TYPESQL_UPDATE;
} else if (x.getAttributeValue(null, "action").equals("delete")) {
typesql = TYPESQL_DELETE;
} else {
typesql = TYPESQL_INSERT;
}
} else {
typesql = TYPESQL_INSERT;
}
if ( x.getAttributeValue(null, "id") != null ) {
id = Long.parseLong(x.getAttributeValue(null, "id"));
}
if (typesql == TYPESQL_INSERT) {
currenEntity = new Entity(x.getAttributeValue(null, "table"));
if (id>0) currenEntity.setForceId(id);
} else if (typesql == TYPESQL_UPDATE) {
if (id>0) currenEntity = new Entity(x.getAttributeValue(null, "table"), id);
} else {
if (id>0) currenEntity = new Entity(x.getAttributeValue(null, "table"), id);
}
}
}
if (x.getName().equals("field")) {
if ( x.getAttributeValue(null, "lang") != null ) {
if ( ( x.getAttributeValue(null, "name") != null ) && ( x.getAttributeValue(null, "value") != null ) ) {
if (currenEntity!=null) currenEntity.setMultilanguageValue(x.getAttributeValue(null, "name"),
x.getAttributeValue(null, "lang"),
x.getAttributeValue(null, "value"));
}
} else {
if ( ( x.getAttributeValue(null, "name") != null ) && ( x.getAttributeValue(null, "value") != null ) ) {
if (currenEntity!=null) {
if (x.getAttributeValue(null, "value")!=null) {
currenEntity.setValue(x.getAttributeValue(null, "name"),
x.getAttributeValue(null, "value").replace("&quot;", "\""));
}
}
}
}
}
}
if ( eventType == XmlPullParser.END_TAG ) {
if (x.getName().equals("row")) {
if (currenEntity!=null) {
if (typesql == TYPESQL_DELETE) {
currenEntity.delete();
} else {
currenEntity.save();
}
}
}
}
eventType = x.next();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Devuelve conexion a SQLiteDatabase
*
* @return objeto SQLiteDatabase
*/
public SQLiteDatabase getDB() {
return mDb;
}
public Context getContext()
{
return mCtx;
}
public String getPackage() {
return mPackage;
}
/**
* Establece el lenguaje a usar
*
* @param lang Lenguaje
*/
public void setForceLanguage(String lang) {
if (mLanguages.contains(lang)) mCurrentLanguage = lang;
}
public ArrayList<String> getLanguages() {
return mLanguages;
}
public String getCurrentLanguage() {
return mCurrentLanguage;
}
}

View File

@ -1,240 +0,0 @@
/*
* Copyright (C) 2008 Javier Perez Pacheco y Javier Ros Moreno
*
* Android Data Framework: Trabajo con BD SQLite en Android
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Javier Perez Pacheco
* Cadiz (Spain)
* javi.pacheco@gmail.com
*
* Javier Ros Moreno
* jros@jros.org
*
*
*/
package com.android.dataframework.core;
public class Field {
private String mName;
private String mType;
private boolean mObligatory;
private int mSize;
private int mNewInVersion;
private String mForeignTable;
private String mTextDefault;
/**
* Constructor - Crea un campo mediante un nombre
*
* @param name nombre del campo
*/
public Field (String name) {
this.mName = name;
this.mType = "string";
this.mObligatory = false;
this.mSize = -1;
this.mForeignTable = "";
this.mTextDefault = null;
mNewInVersion = 1;
}
/**
* Devuelve el tipo SQL
*
* @return tipo sql
*/
public String getSQLType()
{
String type = mType;
int size = mSize;
String out = "";
if ( (type.equals("text") || type.equals("multilanguage") || type.equals("string-identifier")) && (size>0) ) {
out += " varchar(" + mSize + ")";
} else if ( (type.equals("text") || type.equals("multilanguage") || type.equals("string-identifier")) && (size <= 0) ) {
out += " text";
} else if (type.equals("drawable-identifier")) {
out += " varchar(128)";
} else if (type.equals("foreign-key")) {
out += " integer";
} else {
out += " " + type;
}
return out;
}
/**
* Devuelve el campo ALTER TABLE
*
* @return tipo sql
*/
public String getSQLAddField()
{
String sql = "";
sql += " " + getSQLType();
if (mObligatory)
sql += " not null";
if (mTextDefault!=null) {
sql += " DEFAULT '" + mTextDefault + "'";
}
return sql;
}
/**
* Devuelve el nombre
*
* @return nombre
*/
public String getName() {
return mName;
}
/**
* Establece el nombre
*
* @param name nombre
*/
public void setName(String name) {
this.mName = name;
}
/**
* Devuelve el tipo
*
* @return tipo
*/
public String getType() {
return mType;
}
/**
* Establece el tipo
*
* @param type tipo
*/
public void setType(String type) {
this.mType = type;
}
/**
* Devuelve si el campo es obligatorio
*
* @return true o false
*/
public boolean isObligatory() {
return mObligatory;
}
/**
* Establece el campo obligatorio
*
* @param true o false
*/
public void setObligatory(boolean obligatory) {
this.mObligatory = obligatory;
}
/**
* Devuelve el tamano
*
* @return tama<EFBFBD>o
*/
public int getSize() {
return mSize;
}
/**
* Establece el tamano
*
* @param tamano
*/
public void setSize(int size) {
this.mSize = size;
}
/**
* Devuelve la tabla a la que pertenece la clave foranea
*
* @return tabla
*/
public String getForeignTable() {
return mForeignTable;
}
/**
* Establece la tabla a la que pertenece la clave foranea
*
* @param tabla
*/
public void setForeignTable(String foreignTable) {
this.mForeignTable = foreignTable;
}
/**
* Devuelve la versi<EFBFBD>n en la que ha sido creado
*
* @return version
*/
public int getNewInVersion() {
return mNewInVersion;
}
/**
* Establece la versi<EFBFBD>n en la que ha sido creado
*
* @return version
*/
public void setNewInVersion(int newInVersion) {
this.mNewInVersion = newInVersion;
}
/**
* Devuelve el texto por defecto
*
* @return texto por defecto
*/
public String getTextDefault() {
return mTextDefault;
}
/**
* Establece el texto por defecto
*
* @param texto por defecto
*/
public void setTextDefault(String textDefault) {
this.mTextDefault = textDefault;
}
}

View File

@ -1,294 +0,0 @@
/*
* Copyright (C) 2008 Javier Perez Pacheco y Javier Ros Moreno
*
* Android Data Framework: Trabajo con BD SQLite en Android
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Javier Perez Pacheco
* Cadiz (Spain)
* javi.pacheco@gmail.com
*
* Javier Ros Moreno
* jros@jros.org
*
*
*/
package com.android.dataframework.core;
import com.android.dataframework.DataFramework;
import java.util.ArrayList;
public class Table {
private String mName;
private String mToString;
private ArrayList<Field> mFields = new ArrayList<>();
private int mNewInVersion;
private boolean mBackup;
/**
* Constructor - Contiene la informacion de una tabla de la base de datos
*
* @param name nombre de la tabla
*/
public Table (String name) {
mName = name;
mBackup = true;
mToString = "";
mNewInVersion = 1;
}
/**
* Devuelve la sentencia SQL para crear la tabla
*
* @return sql
*/
public String getSQLCreateTable ()
{
String out = "create table " + mName + " (_id integer primary key";
ArrayList<Field> fields = mFields;
int fieldCount = fields.size();
for (int i=0; i < fieldCount; i++)
{
Field f = fields.get(i);
if (f.getType().equals("multilanguage")) {
ArrayList<String> langs = DataFramework.getInstance().getLanguages();
for (int j=0; j<langs.size(); j++) {
out += ", " + f.getName() + "_" + langs.get(j);
out += " " + f.getSQLType();
if (f.isObligatory()){
out += " not null";
}
if (f.getTextDefault()!=null) {
out += " DEFAULT '" + f.getTextDefault() + "'";
}
}
} else {
out += ", " + f.getName();
out += " " + f.getSQLType();
if (f.isObligatory()){
out += " not null";
}
if (f.getTextDefault()!=null) {
out += " DEFAULT '" + f.getTextDefault() + "'";
}
}
}
out += ");";
return out;
}
/**
* Devuelve la sentencia SQL para modificar el campo de la tabla
*
* @param field Campo a tratar
* @return sql
*/
public String getSQLAddField (Field field) {
if (field!=null) {
String out = "";
if (field.getType().equals("multilanguage")) {
ArrayList<String> langs = DataFramework.getInstance().getLanguages();
for (int j=0; j<langs.size(); j++) {
out += "ALTER TABLE " + mName + " ADD " + field.getName() + "_" + langs.get(j) + field.getSQLAddField() + ";";
}
} else {
out = "ALTER TABLE " + mName + " ADD " + field.getName() + " " + field.getSQLAddField();
}
return out;
}
return null;
}
/**
* Devuelve la sentecia SQL para borrar la tabla
*
* @return sql
*/
public String getSQLDeleteTable () {
return "DROP TABLE IF EXISTS " + mName;
}
/**
* Devuelve una lista con los campos de la tabla
*
* @return lista de objetos Field
*/
public ArrayList<Field> getFields() {
return mFields;
}
/**
* Devuelve un array con los nombres de los campos de la tabla
*
* @return array con los nombres
*/
public String[] getFieldsToArray()
{
ArrayList<Field> fields = mFields;
int fieldCount = fields.size();
ArrayList<String> aux = new ArrayList<>();
aux.add(DataFramework.KEY_ID);
for (int i = 0; i < fieldCount; i++) {
if (fields.get(i).getType().equals("multilanguage")) {
ArrayList<String> langs = DataFramework.getInstance().getLanguages();
for (int j=0; j<langs.size(); j++) {
aux.add(fields.get(i).getName() + "_" + langs.get(j));
}
} else {
aux.add(fields.get(i).getName());
}
}
String[] out = new String[aux.size()];
for (int i = 0; i < aux.size(); i++) {
out[i] = aux.get(i);
}
return out;
}
/**
* Devuelve el objeto Field del nombre de un campo
*
* @param name nombre del campo
* @return objeto Field
*/
public Field getField(String name) {
Field res = null;
ArrayList<Field> fields = mFields;
int fieldCount = fields.size();
for (int i=0; i<fieldCount; i++)
{
Field f = fields.get(i);
if (f.getName().equals(name)){
res = f;
}
}
if(res==null){
throw new NullPointerException("No exist field '"+name+"' in table '"+mName+"'");
}
return res;
}
/**
* Devuelve el nombre de la tabla
*
* @return nombre
*/
public String getName() {
return mName;
}
/**
* Establece el nombre de la tabla
*
* @param name nombre
*/
public void setName(String name) {
this.mName = name;
}
/**
* Agrega un campo a la tabla
*
* @param field Objeto Field
*/
public void addField(Field field) {
mFields.add(field);
}
/**
* Devuelve el formato del toString()
*
* @return formato
*/
public String getToString() {
return mToString;
}
/**
* Establece el formato del toString()
*
* @param toString formato toString()
*/
public void setToString(String toString) {
this.mToString = toString;
}
/**
* Devuelve la version en la que ha sido creado
*
* @return version
*/
public int getNewInVersion() {
return mNewInVersion;
}
/**
* Establece la version en la que ha sido creado
*
* @return version
*/
public void setNewInVersion(int newInVersion) {
this.mNewInVersion = newInVersion;
}
/**
* Devuelve si se tiene que hacer backups de esta table
*
* @return boolean
*/
public boolean isBackup() {
return mBackup;
}
/**
* Establece si se tiene que hacer backups de esta table
*
* @param backup
*/
public void setBackup(boolean backup) {
this.mBackup = backup;
}
}

View File

@ -21,7 +21,7 @@ package es.ugr.swad.swadroid;
/** /**
* Application settings. * Application settings.
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class Config { public class Config {
/** /**

View File

@ -26,7 +26,7 @@ import java.io.File;
/** /**
* Constants of application. * Constants of application.
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
* @author Antonio Aguilera Malagon <aguilerin@gmail.com> * @author Antonio Aguilera Malagon <aguilerin@gmail.com>
* @author Helena Rodriguez Gijon <hrgijon@gmail.com> * @author Helena Rodriguez Gijon <hrgijon@gmail.com>
* @author Jose Antonio Guerrero Aviles <cany20@gmail.com> * @author Jose Antonio Guerrero Aviles <cany20@gmail.com>
@ -61,9 +61,10 @@ public class Constants {
*/ */
public static final int CONNECTION_TIMEOUT = 60000; public static final int CONNECTION_TIMEOUT = 60000;
/** /**
* Threshold for clean old notifications (in seconds) * Threshold for clean old notifications (in days)
*/ */
public static final int CLEAN_NOTIFICATIONS_THRESHOLD = 2592000; // 30 days //public static final int CLEAN_NOTIFICATIONS_THRESHOLD = 2592000; // 30 days
public static final int CLEAN_NOTIFICATIONS_THRESHOLD = 2592000;
/** /**
* Null value returned by webservices when a field is empty * Null value returned by webservices when a field is empty
*/ */

View File

@ -43,24 +43,23 @@ import android.widget.Spinner;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import es.ugr.swad.swadroid.database.DataBaseHelper; import es.ugr.swad.swadroid.dao.CourseDao;
import es.ugr.swad.swadroid.database.AppDatabase;
import es.ugr.swad.swadroid.gui.DialogFactory; import es.ugr.swad.swadroid.gui.DialogFactory;
import es.ugr.swad.swadroid.gui.MenuExpandableListActivity; import es.ugr.swad.swadroid.gui.MenuExpandableListActivity;
import es.ugr.swad.swadroid.gui.ProgressScreen; import es.ugr.swad.swadroid.gui.ProgressScreen;
import es.ugr.swad.swadroid.gui.TextExpandableListAdapter; import es.ugr.swad.swadroid.gui.TextExpandableListAdapter;
import es.ugr.swad.swadroid.model.Course; import es.ugr.swad.swadroid.model.Course;
import es.ugr.swad.swadroid.model.Model;
import es.ugr.swad.swadroid.modules.courses.Courses; import es.ugr.swad.swadroid.modules.courses.Courses;
import es.ugr.swad.swadroid.modules.downloads.DownloadsManager; import es.ugr.swad.swadroid.modules.downloads.DownloadsManager;
import es.ugr.swad.swadroid.modules.groups.MyGroupsManager; import es.ugr.swad.swadroid.modules.groups.MyGroupsManager;
import es.ugr.swad.swadroid.modules.information.Information;
import es.ugr.swad.swadroid.modules.indoorlocation.IndoorLocation; import es.ugr.swad.swadroid.modules.indoorlocation.IndoorLocation;
import es.ugr.swad.swadroid.modules.information.Information;
import es.ugr.swad.swadroid.modules.login.Login; import es.ugr.swad.swadroid.modules.login.Login;
import es.ugr.swad.swadroid.modules.login.LoginActivity; import es.ugr.swad.swadroid.modules.login.LoginActivity;
import es.ugr.swad.swadroid.modules.messages.Messages; import es.ugr.swad.swadroid.modules.messages.Messages;
@ -78,7 +77,7 @@ import es.ugr.swad.swadroid.utils.Utils;
/** /**
* Main class of the application. * Main class of the application.
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
* @author Antonio Aguilera Malagon <aguilerin@gmail.com> * @author Antonio Aguilera Malagon <aguilerin@gmail.com>
* @author Helena Rodriguez Gijon <hrgijon@gmail.com> * @author Helena Rodriguez Gijon <hrgijon@gmail.com>
* @author Jose Antonio Guerrero Aviles <cany20@gmail.com> * @author Jose Antonio Guerrero Aviles <cany20@gmail.com>
@ -99,7 +98,7 @@ public class SWADMain extends MenuExpandableListActivity {
/** /**
* User courses list * User courses list
*/ */
private List<Model> listCourses; private List<Course> listCourses;
/** /**
* SWADMain tag name for Logcat * SWADMain tag name for Logcat
*/ */
@ -110,6 +109,10 @@ public class SWADMain extends MenuExpandableListActivity {
*/ */
private boolean firstRun = false; private boolean firstRun = false;
/**
* DAO for Courses
*/
private CourseDao courseDao;
/** /**
* Current role 2 - student 3 - teacher -1 - none role was chosen * Current role 2 - student 3 - teacher -1 - none role was chosen
@ -130,15 +133,6 @@ public class SWADMain extends MenuExpandableListActivity {
private ProgressScreen mProgressScreen; private ProgressScreen mProgressScreen;
/**
* Gets the database helper
*
* @return the database helper
*/
public static DataBaseHelper getDbHelper() {
return dbHelper;
}
/** /**
* Shows initial dialog after application upgrade. * Shows initial dialog after application upgrade.
* *
@ -157,11 +151,15 @@ public class SWADMain extends MenuExpandableListActivity {
*/ */
@Override @Override
public void onCreate(Bundle icicle) { public void onCreate(Bundle icicle) {
int lastVersion, currentVersion; int lastVersion;
int currentVersion;
//Initialize screen //Initialize screen
super.onCreate(icicle); super.onCreate(icicle);
//Initialize DAOs
courseDao = db.getCourseDao();
setContentView(R.layout.main); setContentView(R.layout.main);
initializeMainViews(); initializeMainViews();
@ -169,7 +167,6 @@ public class SWADMain extends MenuExpandableListActivity {
//Check if this is the first run after an install or upgrade //Check if this is the first run after an install or upgrade
lastVersion = Preferences.getLastVersion(); lastVersion = Preferences.getLastVersion();
currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode; currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
dbHelper.initializeDB();
//lastVersion = 67; //lastVersion = 67;
//currentVersion = 68; //currentVersion = 68;
@ -202,8 +199,8 @@ public class SWADMain extends MenuExpandableListActivity {
if (isUserOrPasswordEmpty() && listCourses.isEmpty()) { if (isUserOrPasswordEmpty() && listCourses.isEmpty()) {
startActivityForResult(new Intent(this, LoginActivity.class), Constants.LOGIN_REQUEST_CODE); startActivityForResult(new Intent(this, LoginActivity.class), Constants.LOGIN_REQUEST_CODE);
} else { } else {
if(Preferences.isPreferencesChanged() || DataBaseHelper.isDbCleaned()) { if(Preferences.isPreferencesChanged() || AppDatabase.isDbCleaned()) {
DataBaseHelper.setDbCleaned(false); AppDatabase.setDbCleaned(false);
Preferences.setPreferencesChanged(false); Preferences.setPreferencesChanged(false);
Preferences.initializeSelectedCourse(); Preferences.initializeSelectedCourse();
@ -262,30 +259,9 @@ public class SWADMain extends MenuExpandableListActivity {
* @param lastVersion Version from which the application is updated * @param lastVersion Version from which the application is updated
* @param currentVersion Version to which the application is updated * @param currentVersion Version to which the application is updated
*/ */
private void upgradeApp(int lastVersion, int currentVersion) throws NoSuchAlgorithmException { private void upgradeApp(int lastVersion, int currentVersion) {
Log.i(TAG, "Upgrading application from version " + lastVersion + " to version " + currentVersion); Log.i(TAG, "Upgrading application from version " + lastVersion + " to version " + currentVersion);
dbHelper.upgradeDB();
if(lastVersion < 52) {
//Encrypts users table
dbHelper.encryptUsers();
//If the app is updating from an unencrypted user password version, encrypt user password
Preferences.upgradeCredentials();
Preferences.setSyncTime(String.valueOf(Constants.DEFAULT_SYNC_TIME));
}
if(lastVersion < 57) {
//Reconfigure automatic synchronization
SyncUtils.removePeriodicSync(Constants.AUTHORITY, Bundle.EMPTY, this);
if(!Preferences.getSyncTime().equals("0") && Preferences.isSyncEnabled()) {
SyncUtils.addPeriodicSync(Constants.AUTHORITY, Bundle.EMPTY,
Long.valueOf(Preferences.getSyncTime()), this);
}
}
Preferences.setLastVersion(currentVersion); Preferences.setLastVersion(currentVersion);
Log.i(TAG, "Application upgraded from version " + lastVersion + " to version " + currentVersion); Log.i(TAG, "Application upgraded from version " + lastVersion + " to version " + currentVersion);
@ -333,11 +309,11 @@ public class SWADMain extends MenuExpandableListActivity {
} }
private void createSpinnerAdapter() { private void createSpinnerAdapter() {
listCourses = dbHelper.getAllRows(DataBaseHelper.DB_TABLE_COURSES, null, "shortName"); listCourses = courseDao.findAllOrderedByShortNameAsc();
/* /*
Cursor for database access Cursor for database access
*/ */
Cursor dbCursor = dbHelper.getDb().getCursor(DataBaseHelper.DB_TABLE_COURSES, null, "shortName"); Cursor dbCursor = courseDao.findAllOrderedByShortNameAscCursor();
startManagingCursor(dbCursor); startManagingCursor(dbCursor);
if (!listCourses.isEmpty()) { if (!listCourses.isEmpty()) {
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
@ -355,7 +331,7 @@ public class SWADMain extends MenuExpandableListActivity {
else else
mCoursesSpinner.setSelection(0); mCoursesSpinner.setSelection(0);
mCoursesSpinner.setOnTouchListener(Spinner_OnTouch); mCoursesSpinner.setOnTouchListener(spinnerOnTouch);
mCoursesSpinner.setVisibility(View.VISIBLE); mCoursesSpinner.setVisibility(View.VISIBLE);
Log.i(TAG, "Created Spinner adapter"); Log.i(TAG, "Created Spinner adapter");
@ -370,7 +346,7 @@ public class SWADMain extends MenuExpandableListActivity {
private void cleanSpinner() { private void cleanSpinner() {
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]{getString(R.string.clickToGetCourses)}); ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new String[]{getString(R.string.clickToGetCourses)});
mCoursesSpinner.setAdapter(adapter); mCoursesSpinner.setAdapter(adapter);
mCoursesSpinner.setOnTouchListener(Spinner_OnTouch); mCoursesSpinner.setOnTouchListener(spinnerOnTouch);
Log.i(TAG, "Cleaned Spinner adapter"); Log.i(TAG, "Cleaned Spinner adapter");
} }
@ -382,7 +358,7 @@ public class SWADMain extends MenuExpandableListActivity {
if (!listCourses.isEmpty()) { if (!listCourses.isEmpty()) {
Preferences.setLastCourseSelected(position); Preferences.setLastCourseSelected(position);
Course courseSelected = (Course) listCourses.get(position); Course courseSelected = listCourses.get(position);
courseCode = courseSelected.getId(); courseCode = courseSelected.getId();
@ -398,16 +374,14 @@ public class SWADMain extends MenuExpandableListActivity {
@Override @Override
public void onNothingSelected(AdapterView<?> arg0) { public void onNothingSelected(AdapterView<?> arg0) {
// No-op
} }
} }
private final View.OnTouchListener Spinner_OnTouch = new View.OnTouchListener() { private final View.OnTouchListener spinnerOnTouch = (v, event) -> {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) { if (event.getAction() == MotionEvent.ACTION_UP) {
if (dbHelper.getAllRows(DataBaseHelper.DB_TABLE_COURSES).isEmpty()) { if (courseDao.findAllOrderedByShortNameAsc().isEmpty()) {
if (Utils.connectionAvailable(getApplicationContext())) if (Utils.connectionAvailable(getApplicationContext()))
getCurrentCourses(); getCurrentCourses();
} else { } else {
@ -415,7 +389,6 @@ public class SWADMain extends MenuExpandableListActivity {
} }
} }
return true; return true;
}
}; };
private void getCurrentCourses() { private void getCurrentCourses() {
@ -432,7 +405,7 @@ public class SWADMain extends MenuExpandableListActivity {
Course courseSelected; Course courseSelected;
if (Courses.getSelectedCourseCode() != -1) { if (Courses.getSelectedCourseCode() != -1) {
courseSelected = dbHelper.getRow(DataBaseHelper.DB_TABLE_COURSES, "id", String.valueOf(Courses.getSelectedCourseCode())); courseSelected = courseDao.findCourseById(Courses.getSelectedCourseCode());
Log.i(TAG + " createMenu", "Recovered selected course " + courseSelected + " from database"); Log.i(TAG + " createMenu", "Recovered selected course " + courseSelected + " from database");
} else { } else {
@ -441,12 +414,12 @@ public class SWADMain extends MenuExpandableListActivity {
int lastSelected = Preferences.getLastCourseSelected(); int lastSelected = Preferences.getLastCourseSelected();
if (lastSelected != -1 && lastSelected < listCourses.size()) { if (lastSelected != -1 && lastSelected < listCourses.size()) {
courseSelected = (Course) listCourses.get(lastSelected); courseSelected = listCourses.get(lastSelected);
Preferences.setLastCourseSelected(lastSelected); Preferences.setLastCourseSelected(lastSelected);
Log.i(TAG + " createMenu", "Setted last course selected to " + courseSelected); Log.i(TAG + " createMenu", "Setted last course selected to " + courseSelected);
} else { } else {
courseSelected = (Course) listCourses.get(0); courseSelected = listCourses.get(0);
Preferences.setLastCourseSelected(0); Preferences.setLastCourseSelected(0);
Log.w(TAG + " createMenu", "No last course selected. Initialized last course selected to " + courseSelected); Log.w(TAG + " createMenu", "No last course selected. Initialized last course selected to " + courseSelected);
@ -653,14 +626,9 @@ public class SWADMain extends MenuExpandableListActivity {
mProgressScreen = new ProgressScreen(mProgressScreenView, mCoursesListView, mProgressScreen = new ProgressScreen(mProgressScreenView, mCoursesListView,
getString(R.string.coursesProgressDescription), this); getString(R.string.coursesProgressDescription), this);
OnChildClickListener mExpandableClickListener = new OnChildClickListener() { OnChildClickListener mExpandableClickListener = (parent, v, groupPosition, childPosition, id) -> {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
int childPosition, long id) {
// Get the item that was clicked // Get the item that was clicked
Object o = parent.getExpandableListAdapter().getChild(groupPosition, childPosition); Object o = parent.getExpandableListAdapter().getChild(groupPosition, childPosition);
@SuppressWarnings("unchecked")
String keyword = (String) ((Map<String, Object>) o).get(NAME); String keyword = (String) ((Map<String, Object>) o).get(NAME);
Intent activity; Intent activity;
Context ctx = getApplicationContext(); Context ctx = getApplicationContext();
@ -742,7 +710,6 @@ public class SWADMain extends MenuExpandableListActivity {
} }
return true; return true;
}
}; };
mExpandableListView.setOnChildClickListener(mExpandableClickListener); mExpandableListView.setOnChildClickListener(mExpandableClickListener);
@ -787,9 +754,9 @@ public class SWADMain extends MenuExpandableListActivity {
} }
private void loadCourses() { private void loadCourses() {
listCourses = dbHelper.getAllRows(DataBaseHelper.DB_TABLE_COURSES, "", "shortName"); listCourses = courseDao.findAllOrderedByShortNameAsc();
if (!listCourses.isEmpty()) { if (!listCourses.isEmpty()) {
Course c = (Course) listCourses.get(0); Course c = listCourses.get(0);
Courses.setSelectedCourseCode(c.getId()); Courses.setSelectedCourseCode(c.getId());
Courses.setSelectedCourseShortName(c.getShortName()); Courses.setSelectedCourseShortName(c.getShortName());

View File

@ -0,0 +1,49 @@
package es.ugr.swad.swadroid.converters;
import android.util.Log;
import androidx.room.TypeConverter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import es.ugr.swad.swadroid.Constants;
/**
* Calendar converter class for database access
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
public class CalendarConverter {
/**
* CalendarConverter tag name for Logcat
*/
private static final String TAG = Constants.APP_TAG + " CalendarConverter";
private static final String DATE_PATTERN = "yyyyMMdd";
@TypeConverter
public static Calendar toCalendar(String calendarString) {
Calendar cal = null;
try {
if((calendarString != null) && !calendarString.isEmpty() && !calendarString.equals("00000000")) {
cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN, Locale.getDefault());
cal.setTime(sdf.parse(calendarString));
}
} catch (ParseException e) {
Log.e(TAG, e.getMessage(), e);
}
return cal;
}
@TypeConverter
public static String fromCalendar(Calendar calendar) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN, Locale.getDefault());
return sdf.format(calendar.getTime());
}
}

View File

@ -0,0 +1,7 @@
<html>
<head>
</head>
<body>
Converters package.
</body>
</html>

View File

@ -0,0 +1,63 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.dao;
import android.database.Cursor;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
import es.ugr.swad.swadroid.model.Course;
/**
* DAO for Course table.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
@Dao
public interface CourseDao {
@Query("SELECT * FROM Course")
List<Course> findAll();
@Query("SELECT * FROM Course ORDER BY shortName ASC")
List<Course> findAllOrderedByShortNameAsc();
@Query("SELECT * FROM Course ORDER BY shortName ASC")
Cursor findAllOrderedByShortNameAscCursor();
@Query("SELECT * FROM Course WHERE id = :id")
Course findCourseById(long id);
@Insert
void insertCourses(List<Course> courses);
@Update
int updateCourses(List<Course> courses);
@Delete
int deleteCourses(List<Course> courses);
@Query("DELETE FROM Course")
int deleteAll();
}

View File

@ -0,0 +1,64 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.dao;
import android.database.Cursor;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
import es.ugr.swad.swadroid.model.Event;
/**
* DAO for Event table.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
@Dao
public interface EventDao {
@Query("SELECT * FROM Event")
List<Event> findAll();
@Query("SELECT * FROM Event WHERE crsCod = :courseCode")
List<Event> findAllByCourseCode(long courseCode);
@Query("SELECT * FROM Event WHERE crsCod = :courseCode")
Cursor findAllByCourseCodeCursor(long courseCode);
@Query("SELECT * FROM Event WHERE id = :id")
Event findById(long id);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertEvents(List<Event> events);
@Update
int updateEvents(List<Event> events);
@Delete
int deleteEvents(List<Event> events);
@Query("DELETE FROM Event")
int deleteAll();
}

View File

@ -0,0 +1,61 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.dao;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
import es.ugr.swad.swadroid.model.FrequentUser;
/**
* DAO for FrequentUser table.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
@Dao
public interface FrequentUserDao {
@Query("SELECT * FROM FrequentUser")
List<FrequentUser> findAll();
@Query("SELECT * FROM FrequentUser WHERE idUser = :idUser")
List<FrequentUser> findByUserByIdUser(String idUser);
@Query("SELECT * FROM FrequentUser WHERE idUser = :idUser ORDER BY score DESC")
List<FrequentUser> findByUserByIdUserOrderByScoreDesc(String idUser);
@Insert
void insertUsers(List<FrequentUser> users);
@Update
int updateUsers(List<FrequentUser> users);
@Delete
int deleteUsers(List<FrequentUser> users);
@Query("DELETE FROM FrequentUser WHERE idUser = :idUser")
int deleteById(String idUser);
@Query("DELETE FROM FrequentUser")
int deleteAll();
}

View File

@ -0,0 +1,76 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.dao;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Transaction;
import androidx.room.Update;
import java.util.List;
import es.ugr.swad.swadroid.model.Group;
import es.ugr.swad.swadroid.model.GroupsCourse;
import es.ugr.swad.swadroid.model.GroupsGroupType;
/**
* DAO for Group table.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
@Dao
public interface GroupDao {
@Query("SELECT * FROM `Group`")
List<Group> findAll();
@Query("SELECT * FROM `Group` WHERE groupTypeCode = :groupTypeCode")
List<Group> findAllByTypeCode(long groupTypeCode);
@Transaction
@Query("SELECT *" +
" FROM `Group`" +
" JOIN GroupType ON `Group`.groupTypeCode = GroupType.id" +
" WHERE `Group`.id = :grpCod")
GroupsGroupType findGroupsGroupTypeByGroupCode(long grpCod);
@Transaction
@Query("SELECT *" +
" FROM `Group`" +
" JOIN Course ON `Group`.crsCod = Course.id" +
" WHERE crsCod = :crsCod")
GroupsCourse findGroupsCourseByCourseCode(long crsCod);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertGroups(List<Group> groups);
@Update
int updateGroups(List<Group> groups);
@Delete
int deleteGroups(List<Group> groups);
@Query("DELETE FROM `Group` WHERE id NOT IN (:ids)")
int deleteGroupsByIdNotIn(List<Long> ids);
@Query("DELETE FROM `Group`")
int deleteAll();
}

View File

@ -0,0 +1,59 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.dao;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
import es.ugr.swad.swadroid.model.GroupType;
/**
* DAO for GroupType table.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
@Dao
public interface GroupTypeDao {
@Query("SELECT * FROM GroupType")
List<GroupType> findAll();
@Query("SELECT * FROM GroupType WHERE courseCode = :courseCode")
List<GroupType> findAllByCourseCode(long courseCode);
@Query("SELECT * FROM GroupType WHERE courseCode = :courseCode ORDER BY groupTypeName")
List<GroupType> findAllByCourseCodeOrderByGroupTypeNameAsc(long courseCode);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertGroupTypes(List<GroupType> groupTypes);
@Update
int updateGroupTypes(List<GroupType> groupTypes);
@Delete
int deleteGroupTypes(List<GroupType> groupTypes);
@Query("DELETE FROM GroupType")
int deleteAll();
}

View File

@ -0,0 +1,34 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.dao;
import androidx.room.Dao;
import androidx.room.RawQuery;
import androidx.sqlite.db.SupportSQLiteQuery;
/**
* DAO for raw queries
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>.
*/
@Dao
public interface RawDao {
@RawQuery
int rawQuery(SupportSQLiteQuery supportSQLiteQuery);
}

View File

@ -0,0 +1,76 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.dao;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
import es.ugr.swad.swadroid.model.SWADNotification;
/**
* DAO for SWADNotification table.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
@Dao
public interface SWADNotificationDao {
@Query("SELECT * FROM SWADNotification")
List<SWADNotification> findAll();
@Query("SELECT * FROM SWADNotification WHERE seenLocal=:seenLocal ORDER BY eventTime DESC")
List<SWADNotification> findAllOrderByEventTimeDesc(boolean seenLocal);
@Query("SELECT * FROM SWADNotification WHERE seenLocal AND NOT seenRemote")
List<SWADNotification> findAllPendingToRead();
@Query("SELECT * FROM SWADNotification WHERE id=:notifCode")
SWADNotification findById(long notifCode);
@Query("SELECT COUNT(*) from SWADNotification")
long countAll();
@Query("SELECT MAX(eventTime) from SWADNotification")
long findMaxEventTime();
@Insert
void insertSWADNotifications(List<SWADNotification> notifications);
@Update
int updateSWADNotifications(List<SWADNotification> notifications);
@Query("UPDATE SWADNotification SET seenLocal=:seenLocal")
int updateAllBySeenLocal(boolean seenLocal);
@Query("UPDATE SWADNotification SET seenRemote=:seenRemote")
int updateAllBySeenRemote(boolean seenRemote);
@Delete
int deleteSWADNotifications(List<SWADNotification> notifications);
@Query("DELETE FROM SWADNotification WHERE eventTime <= strftime('%s','now') - :age")
int deleteAllByAge(long age);
@Query("DELETE FROM SWADNotification")
int deleteAll();
}

View File

@ -0,0 +1,53 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.dao;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
import es.ugr.swad.swadroid.model.TestAnswer;
/**
* DAO for Test answers table.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
@Dao
public interface TestAnswerDao {
@Query("SELECT * FROM TestAnswer")
List<TestAnswer> findAll();
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertTestAnswer(List<TestAnswer> testAnswers);
@Update
int updateTestAnswer(List<TestAnswer> testAnswers);
@Delete
int deleteTestAnswer(List<TestAnswer> testAnswers);
@Query("DELETE FROM TestAnswer")
int deleteAll();
}

View File

@ -0,0 +1,61 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.dao;
import android.database.Cursor;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
import es.ugr.swad.swadroid.model.TestConfig;
/**
* DAO for Test config table.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
@Dao
public interface TestConfigDao {
@Query("SELECT * FROM TestConfig")
List<TestConfig> findAll();
@Query("SELECT * FROM TestConfig WHERE id = :courseCode")
TestConfig findByCourseCode(long courseCode);
@Query("SELECT * FROM TestConfig WHERE id = :courseCode")
Cursor findCursorByCourseCode(long courseCode);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertTestConfig(List<TestConfig> testsConfig);
@Update
int updateTestConfig(List<TestConfig> testsConfig);
@Delete
int deleteTestConfig(List<TestConfig> testsConfig);
@Query("DELETE FROM TestConfig")
int deleteAll();
}

View File

@ -0,0 +1,102 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.dao;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Transaction;
import androidx.room.Update;
import java.util.List;
import es.ugr.swad.swadroid.model.TestAnswersQuestion;
import es.ugr.swad.swadroid.model.TestQuestion;
/**
* DAO for Test questions table.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
@Dao
public interface TestQuestionDao {
@Query("SELECT * FROM TestQuestion")
List<TestQuestion> findAll();
@Transaction
@Query("SELECT DISTINCT TestQuestion.id, TestQuestion.crsCod, TestQuestion.stem, TestQuestion.answerType, TestQuestion.shuffle, TestQuestion.feedback" +
" FROM TestQuestion" +
" JOIN TestAnswer ON TestQuestion.id=TestAnswer.qstCod" +
" WHERE TestQuestion.crsCod=:selectedCourseCode" +
" ORDER BY RANDOM(), TestAnswer.ansInd" +
" LIMIT :maxQuestions")
List<TestAnswersQuestion> findAllCourseQuestionsOrderByRandomAndAnswerIndex(long selectedCourseCode, int maxQuestions);
@Transaction
@Query("SELECT DISTINCT TestQuestion.id, TestQuestion.crsCod, TestQuestion.stem, TestQuestion.answerType, TestQuestion.shuffle, TestQuestion.feedback" +
" FROM TestQuestion" +
" JOIN TestTagsQuestions ON TestQuestion.id=TestTagsQuestions.qstCod" +
" JOIN TestTag ON TestTag.id=TestTagsQuestions.tagCod" +
" JOIN TestAnswer ON TestQuestion.id=TestAnswer.qstCod" +
" WHERE TestQuestion.crsCod=:selectedCourseCode AND TestTag.tagTxt IN (:tagsList)" +
" ORDER BY RANDOM(), TestAnswer.ansInd" +
" LIMIT :maxQuestions")
List<TestAnswersQuestion> findAllCourseQuestionsByTagOrderByRandomAndAnswerIndex(long selectedCourseCode,
List<String> tagsList,
int maxQuestions);
@Transaction
@Query("SELECT DISTINCT TestQuestion.id, TestQuestion.crsCod, TestQuestion.stem, TestQuestion.answerType, TestQuestion.shuffle, TestQuestion.feedback" +
" FROM TestQuestion" +
" JOIN TestAnswer ON TestQuestion.id=TestAnswer.qstCod" +
" WHERE TestQuestion.crsCod=:selectedCourseCode AND TestQuestion.answerType IN (:answerTypesList)" +
" ORDER BY RANDOM(), TestAnswer.ansInd" +
" LIMIT :maxQuestions")
List<TestAnswersQuestion> findAllCourseQuestionsByAnswerTypeOrderByRandomAndAnswerIndex(long selectedCourseCode,
List<String> answerTypesList,
int maxQuestions);
@Transaction
@Query("SELECT DISTINCT TestQuestion.id, TestQuestion.crsCod, TestQuestion.stem, TestQuestion.answerType, TestQuestion.shuffle, TestQuestion.feedback" +
" FROM TestQuestion" +
" JOIN TestTagsQuestions ON TestQuestion.id=TestTagsQuestions.qstCod" +
" JOIN TestTag ON TestTag.id=TestTagsQuestions.tagCod" +
" JOIN TestAnswer ON TestQuestion.id=TestAnswer.qstCod" +
" WHERE TestQuestion.crsCod=:selectedCourseCode AND TestTag.tagTxt IN (:tagsList) AND TestQuestion.answerType IN (:answerTypesList)" +
" ORDER BY RANDOM(), TestAnswer.ansInd" +
" LIMIT :maxQuestions")
List<TestAnswersQuestion> findAllCourseQuestionsByTagAndAnswerTypeOrderByRandomAndAnswerIndex(long selectedCourseCode,
List<String> tagsList,
List<String> answerTypesList,
int maxQuestions);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertTestQuestion(List<TestQuestion> testsQuestion);
@Update
int updateTestQuestion(List<TestQuestion> testsQuestion);
@Delete
int deleteTestQuestion(List<TestQuestion> testsQuestion);
@Query("DELETE FROM TestQuestion")
int deleteAll();
}

View File

@ -0,0 +1,59 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.dao;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
import es.ugr.swad.swadroid.model.TestTag;
/**
* DAO for Test tags table.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
@Dao
public interface TestTagDao {
@Query("SELECT * FROM TestTag")
List<TestTag> findAll();
@Query("SELECT TestTag.id, TestTag.tagTxt" +
" FROM TestTag" +
" JOIN TestTagsQuestions ON TestTag.id=TestTagsQuestions.tagCod" +
" JOIN TestQuestion ON TestTagsQuestions.qstCod=TestQuestion.id AND TestQuestion.crsCod = :selectedCourseCode")
List<TestTag> findAllTagsByCourseOrderByTagInd(long selectedCourseCode);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertTestTag(List<TestTag> testsTag);
@Update
int updateTestTag(List<TestTag> testsTag);
@Delete
int deleteTestTag(List<TestTag> testsTag);
@Query("DELETE FROM TestTag")
int deleteAll();
}

View File

@ -0,0 +1,53 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.dao;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
import es.ugr.swad.swadroid.model.TestTagsQuestions;
/**
* DAO for Test tags questions relation.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
@Dao
public interface TestTagsQuestionsDao {
@Query("SELECT * FROM TestTagsQuestions")
List<TestTagsQuestions> findAll();
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertTestTagQuestion(List<TestTagsQuestions> testsTag);
@Update
int updateTestTagQuestion(List<TestTagsQuestions> testsTag);
@Delete
int deleteTestTagQuestion(List<TestTagsQuestions> testsTag);
@Query("DELETE FROM TestTagsQuestions")
int deleteAll();
}

View File

@ -0,0 +1,61 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.dao;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
import es.ugr.swad.swadroid.model.UserAttendance;
/**
* DAO for UserAttendance table.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
@Dao
public interface UserAttendanceDao {
@Query("SELECT * FROM UserAttendance")
List<UserAttendance> findAll();
@Query("SELECT * FROM UserAttendance WHERE eventCode = :eventCode")
List<UserAttendance> findByEventCode(long eventCode);
@Query("SELECT * FROM UserAttendance WHERE id = :userCode AND eventCode = :eventCode")
UserAttendance findByUserCodeAndEventCode(long userCode, long eventCode);
@Insert
void insertAttendances(List<UserAttendance> attendances);
@Update
int updateAttendances(List<UserAttendance> attendances);
@Delete
int deleteAttendances(List<UserAttendance> attendances);
@Query("DELETE FROM UserAttendance WHERE eventCode = :eventCode")
int deleteAttendancesByEventCode(long eventCode);
@Query("DELETE FROM UserAttendance")
int deleteAll();
}

View File

@ -0,0 +1,62 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.dao;
import android.database.Cursor;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
import es.ugr.swad.swadroid.model.User;
/**
* DAO for User table.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
@Dao
public interface UserDao {
@Query("SELECT * FROM User")
List<User> findAll();
@Query("SELECT * FROM User AS U"
+ " INNER JOIN UserAttendance AS A"
+ " ON U.id = A.id WHERE eventCode = :eventCode")
Cursor findAllByEventCodeCursor(long eventCode);
@Query("SELECT * FROM User WHERE userNickName = :userNickName")
User findUserByUserNickname(String userNickName);
@Insert
void insertUsers(List<User> users);
@Update
int updateUsers(List<User> users);
@Delete
int deleteUsers(List<User> users);
@Query("DELETE FROM User")
int deleteAll();
}

View File

@ -0,0 +1,7 @@
<html>
<head>
</head>
<body>
Database access objects package.
</body>
</html>

View File

@ -0,0 +1,218 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.database;
import android.content.Context;
import android.util.Log;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SimpleSQLiteQuery;
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SupportFactory;
import java.nio.charset.StandardCharsets;
import es.ugr.swad.swadroid.Constants;
import es.ugr.swad.swadroid.dao.CourseDao;
import es.ugr.swad.swadroid.dao.EventDao;
import es.ugr.swad.swadroid.dao.FrequentUserDao;
import es.ugr.swad.swadroid.dao.GroupDao;
import es.ugr.swad.swadroid.dao.GroupTypeDao;
import es.ugr.swad.swadroid.dao.RawDao;
import es.ugr.swad.swadroid.dao.SWADNotificationDao;
import es.ugr.swad.swadroid.dao.TestAnswerDao;
import es.ugr.swad.swadroid.dao.TestConfigDao;
import es.ugr.swad.swadroid.dao.TestQuestionDao;
import es.ugr.swad.swadroid.dao.TestTagDao;
import es.ugr.swad.swadroid.dao.TestTagsQuestionsDao;
import es.ugr.swad.swadroid.dao.UserAttendanceDao;
import es.ugr.swad.swadroid.dao.UserDao;
import es.ugr.swad.swadroid.model.Course;
import es.ugr.swad.swadroid.model.Event;
import es.ugr.swad.swadroid.model.FrequentUser;
import es.ugr.swad.swadroid.model.Group;
import es.ugr.swad.swadroid.model.GroupType;
import es.ugr.swad.swadroid.model.Location;
import es.ugr.swad.swadroid.model.LocationTimeStamp;
import es.ugr.swad.swadroid.model.SWADNotification;
import es.ugr.swad.swadroid.model.TestAnswer;
import es.ugr.swad.swadroid.model.TestConfig;
import es.ugr.swad.swadroid.model.TestQuestion;
import es.ugr.swad.swadroid.model.TestTag;
import es.ugr.swad.swadroid.model.TestTagsQuestions;
import es.ugr.swad.swadroid.model.User;
import es.ugr.swad.swadroid.model.UserAttendance;
import es.ugr.swad.swadroid.preferences.Preferences;
import es.ugr.swad.swadroid.utils.Utils;
/**
* Application database.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>.
*/
@Database(entities = {
Course.class,
Event.class,
FrequentUser.class,
Group.class,
GroupType.class,
Location.class,
LocationTimeStamp.class,
SWADNotification.class,
TestAnswer.class,
TestQuestion.class,
TestTag.class,
TestTagsQuestions.class,
TestConfig.class,
User.class,
UserAttendance.class
}, version = 22)
public abstract class AppDatabase extends RoomDatabase {
/**
* Class Module's tag name for Logcat
*/
private static final String TAG = Constants.APP_TAG + " AppDatabase";
private static final String DATABASE_NAME = "swadroid.db";
private static final Object LOCK = new Object();
private static AppDatabase instance;
/**
* Database passphrase
*/
private static String dbKey;
/**
* Indicates if there are changes on db
*/
private static boolean dbCleaned = false;
/**
* Open database
*
* @param context Application context
* @return a database instance
*/
public static AppDatabase getAppDatabase(Context context) {
SupportFactory factory;
try {
if (instance == null) {
synchronized (LOCK) {
SQLiteDatabase.loadLibs(context);
// Create database password if required
createDbKey();
factory = new SupportFactory(dbKey.getBytes(StandardCharsets.UTF_8));
instance =
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, DATABASE_NAME)
.openHelperFactory(factory)
.fallbackToDestructiveMigration()
// TODO Refactor whole app for asynchronous database access and remove allowMainThreadQueries() for production
.allowMainThreadQueries()
.build();
// Migrate from old Database to new Room database if required
MigrationUtils.migrateToRoom(context, dbKey, instance);
}
}
} catch (Exception e) {
// If database migration fails, reset the database
instance.clearAllTables();
Log.e(TAG, "Database migration has failed. Database has been reset", e);
}
return instance;
}
/*
Close database
*/
public static void destroyInstance() {
instance = null;
}
/**
* Vacuum database
*/
public static void vacuumDb() {
instance.getRawDao().rawQuery(new SimpleSQLiteQuery("VACUUM"));
Log.i(TAG, "Database vacuumed successfully");
}
/**
* Indicates if the db was cleaned
*/
public static boolean isDbCleaned() {
return dbCleaned;
}
/**
* Set the fact that the db was cleaned
*/
public static void setDbCleaned(boolean state) {
dbCleaned = state;
}
private static void createDbKey() {
dbKey = Preferences.getDBKey();
// If the passphrase is empty, generate a random passphrase
if (dbKey.equals("")) {
int dbKeyLength = 128;
dbKey = Utils.randomString(dbKeyLength);
Preferences.setDBKey(dbKey);
Log.i(TAG, "DB Key created successfully");
}
}
public abstract RawDao getRawDao();
public abstract CourseDao getCourseDao();
public abstract SWADNotificationDao getSwadNotificationDao();
public abstract UserDao getUserDao();
public abstract UserAttendanceDao getUserAttendanceDao();
public abstract FrequentUserDao getFrequentUserDao();
public abstract EventDao getEventDao();
public abstract GroupDao getGroupDao();
public abstract GroupTypeDao getGroupTypeDao();
public abstract TestConfigDao getTestConfigDao();
public abstract TestTagDao getTestTagDao();
public abstract TestQuestionDao getTestQuestionDao();
public abstract TestAnswerDao getTestAnswerDao();
public abstract TestTagsQuestionsDao getTestTagsQuestionsDao();
}

View File

@ -1,59 +0,0 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.database;
/**
* Exception handler for DataBaseHelper class
*
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*/
public class DataBaseHelperException extends Exception {
private static final long serialVersionUID = 2517884856120859095L;
/**
* Parameterless Constructor
*/
public DataBaseHelperException() {}
/**
* Constructor that accepts a message
* @param detailMessage message to be displayed
*/
public DataBaseHelperException(String detailMessage) {
super(detailMessage);
}
/**
* Constructor that accepts an Exception
* @param throwable Exception to be thrown
*/
public DataBaseHelperException(Throwable throwable) {
super(throwable);
}
/**
* Constructor that accepts a message and an Exception
* @param detailMessage message to be displayed
* @param throwable Exception to be thrown
*/
public DataBaseHelperException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
}

View File

@ -0,0 +1,503 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import es.ugr.swad.swadroid.Constants;
import es.ugr.swad.swadroid.model.Course;
import es.ugr.swad.swadroid.model.Event;
import es.ugr.swad.swadroid.model.FrequentUser;
import es.ugr.swad.swadroid.model.Group;
import es.ugr.swad.swadroid.model.GroupType;
import es.ugr.swad.swadroid.model.SWADNotification;
import es.ugr.swad.swadroid.model.TestAnswer;
import es.ugr.swad.swadroid.model.TestConfig;
import es.ugr.swad.swadroid.model.TestQuestion;
import es.ugr.swad.swadroid.model.TestTag;
import es.ugr.swad.swadroid.model.TestTagsQuestions;
import es.ugr.swad.swadroid.model.User;
import es.ugr.swad.swadroid.model.UserAttendance;
import es.ugr.swad.swadroid.utils.CryptoUtils;
import es.ugr.swad.swadroid.utils.Utils;
public class MigrationUtils {
/**
* Class Module's tag name for Logcat
*/
private static final String TAG = Constants.APP_TAG + " MigrationUtils";
private static final String DATABASE_NAME_OLD = "swadroid_db_crypt";
private static CryptoUtils cryptoUtils;
private static SQLiteDatabase dbOld;
private static AppDatabase db;
public static void migrateToRoom(Context context, String dbKey, AppDatabase instance) throws IOException {
File dbOldFile = context.getDatabasePath(DATABASE_NAME_OLD);
if (dbOldFile.exists()) {
Log.i(TAG, "Migrating old database " + DATABASE_NAME_OLD + " to Room");
cryptoUtils = new CryptoUtils(dbKey);
db = instance;
dbOld = SQLiteDatabase.openDatabase(dbOldFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
Log.d(TAG, "Opened old database " + DATABASE_NAME_OLD + " in READONLY mode");
migrateCourseTableToRoom();
migrateGroupTypeTableToRoom();
migrateGroupTableToRoom();
migrateEventTableToRoom();
migrateUserTableToRoom();
migrateUserAttendanceTableToRoom();
migrateFrequentUserTableToRoom();
migrateSWADNotificationTableToRoom();
migrateTestConfigTableToRoom();
migrateTesTagTableToRoom();
migrateTestQuestionTableToRoom();
migrateTesTagsQuestionsToRoom();
migrateTestAnswerTableToRoom();
dbOld.close();
Log.d(TAG, "Closed old database " + DATABASE_NAME_OLD);
if (context.deleteDatabase(DATABASE_NAME_OLD)) {
Log.i(TAG, "Old database " + DATABASE_NAME_OLD + " deleted successfully");
} else {
throw new IOException("Error deleting old database " + DATABASE_NAME_OLD);
}
Log.i(TAG, DATABASE_NAME_OLD + " database migration to Room completed successfully");
} else {
Log.i(TAG, "Old database " + DATABASE_NAME_OLD + " not present. Database already migrated. Migration skipped");
}
}
private static void migrateCourseTableToRoom() {
String tableName = "courses";
String query = "SELECT * FROM " + tableName;
List<Course> list = new ArrayList<>();
Log.d(TAG, "Migrating " + tableName + " table");
Cursor c = dbOld.rawQuery(query, null);
while (c.moveToNext()) {
Course item = new Course(
c.getLong(c.getColumnIndex("id")),
c.getInt(c.getColumnIndex("userRole")),
c.getString(c.getColumnIndex("shortName")),
c.getString(c.getColumnIndex("fullName"))
);
list.add(item);
}
c.close();
if (!list.isEmpty()) {
db.getCourseDao().insertCourses(list);
}
Log.d(TAG, tableName + " table migrated successfully");
}
private static void migrateGroupTypeTableToRoom() {
String tableName = "group_types";
String query = "SELECT * FROM " + tableName;
List<GroupType> list = new ArrayList<>();
Log.d(TAG, "Migrating " + tableName + " table");
Cursor c = dbOld.rawQuery(query, null);
while (c.moveToNext()) {
GroupType item = new GroupType(
c.getLong(c.getColumnIndex("id")),
c.getString(c.getColumnIndex("groupTypeName")),
c.getLong(c.getColumnIndex("courseCode")),
c.getInt(c.getColumnIndex("mandatory")),
c.getInt(c.getColumnIndex("multiple")),
c.getLong(c.getColumnIndex("openTime"))
);
list.add(item);
}
c.close();
if (!list.isEmpty()) {
db.getGroupTypeDao().insertGroupTypes(list);
}
Log.d(TAG, tableName + " table migrated successfully");
}
private static void migrateGroupTableToRoom() {
String tableName = "groups";
String query = "SELECT * FROM " + tableName + " g" +
" INNER JOIN group_grouptypes ggt ON g.id = ggt.grpCod" +
" INNER JOIN group_types gt ON gt.id = ggt.grpTypCod";
List<Group> list = new ArrayList<>();
Log.d(TAG, "Migrating " + tableName + " table");
Cursor c = dbOld.rawQuery(query, null);
while (c.moveToNext()) {
Group item = new Group(
c.getLong(c.getColumnIndex("g.id")),
c.getString(c.getColumnIndex("groupName")),
c.getLong(c.getColumnIndex("ggt.grpTypCod")),
c.getLong(c.getColumnIndex("gt.courseCode")),
c.getInt(c.getColumnIndex("maxStudents")),
c.getInt(c.getColumnIndex("open")),
c.getInt(c.getColumnIndex("students")),
c.getInt(c.getColumnIndex("fileZones")),
c.getInt(c.getColumnIndex("member"))
);
list.add(item);
}
c.close();
if (!list.isEmpty()) {
db.getGroupDao().insertGroups(list);
}
Log.d(TAG, tableName + " table migrated successfully");
}
private static void migrateEventTableToRoom() {
String tableName = "events_attendances";
String query = "SELECT * FROM " + tableName + " e" +
" INNER JOIN events_courses ec ON e.id = ec.eventCode";
List<Event> list = new ArrayList<>();
Log.d(TAG, "Migrating " + tableName + " table");
Cursor c = dbOld.rawQuery(query, null);
while (c.moveToNext()) {
Event item = new Event(
c.getLong(c.getColumnIndex("g.id")),
c.getLong(c.getColumnIndex("ec.crsCod")),
Utils.parseIntBool(c.getInt(c.getColumnIndex("hidden"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("userSurname1"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("userSurname2"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("userFirstName"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("userPhoto"))),
c.getLong(c.getColumnIndex("startTime")),
c.getLong(c.getColumnIndex("endTime")),
Utils.parseIntBool(c.getInt(c.getColumnIndex("commentsTeachersVisible"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("title"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("text"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("groups"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("status")))
);
list.add(item);
}
c.close();
if (!list.isEmpty()) {
db.getEventDao().insertEvents(list);
}
Log.d(TAG, tableName + " table migrated successfully");
}
private static void migrateUserTableToRoom() {
String tableName = "users";
String query = "SELECT * FROM " + tableName;
List<User> list = new ArrayList<>();
Log.d(TAG, "Migrating " + tableName + " table");
Cursor c = dbOld.rawQuery(query, null);
while (c.moveToNext()) {
User item = new User(
c.getLong(c.getColumnIndex("id")),
c.getString(c.getColumnIndex("wsKey")),
c.getString(c.getColumnIndex("userID")),
c.getString(c.getColumnIndex("userNickname")),
c.getString(c.getColumnIndex("userSurname1")),
c.getString(c.getColumnIndex("userSurname2")),
c.getString(c.getColumnIndex("userFirstname")),
c.getString(c.getColumnIndex("photoPath")),
c.getString(c.getColumnIndex("userBirthday")),
c.getInt(c.getColumnIndex("userRole"))
);
list.add(item);
}
c.close();
if (!list.isEmpty()) {
db.getUserDao().insertUsers(list);
}
Log.d(TAG, tableName + " table migrated successfully");
}
private static void migrateUserAttendanceTableToRoom() {
String tableName = "users_attendances";
String query = "SELECT * FROM " + tableName;
List<UserAttendance> list = new ArrayList<>();
Log.d(TAG, "Migrating " + tableName + " table");
Cursor c = dbOld.rawQuery(query, null);
while (c.moveToNext()) {
UserAttendance item = new UserAttendance(
c.getLong(c.getColumnIndex("id")),
c.getInt(c.getColumnIndex("eventCode")),
Utils.parseIntBool(c.getInt(c.getColumnIndex("present")))
);
list.add(item);
}
c.close();
if (!list.isEmpty()) {
db.getUserAttendanceDao().insertAttendances(list);
}
Log.d(TAG, tableName + " table migrated successfully");
}
private static void migrateFrequentUserTableToRoom() {
String tableName = "frequent_recipients";
String query = "SELECT * FROM " + tableName;
List<FrequentUser> list = new ArrayList<>();
Log.d(TAG, "Migrating " + tableName + " table");
Cursor c = dbOld.rawQuery(query, null);
while (c.moveToNext()) {
FrequentUser item = new FrequentUser(
c.getLong(c.getColumnIndex("id")),
c.getString(c.getColumnIndex("idUser")),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("nicknameRecipient"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("surname1Recipient"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("surname2Recipient"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("firstnameRecipient"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("photoRecipient"))),
c.getInt(c.getColumnIndex("userCode")),
Utils.parseIntBool(c.getInt(c.getColumnIndex("selectedCheckbox"))),
c.getDouble(c.getColumnIndex("score"))
);
list.add(item);
}
c.close();
if (!list.isEmpty()) {
db.getFrequentUserDao().insertUsers(list);
}
Log.d(TAG, tableName + " table migrated successfully");
}
private static void migrateSWADNotificationTableToRoom() {
String tableName = "notifications";
String query = "SELECT * FROM " + tableName;
List<SWADNotification> list = new ArrayList<>();
Log.d(TAG, "Migrating " + tableName + " table");
Cursor c = dbOld.rawQuery(query, null);
while (c.moveToNext()) {
String nickName = c.getString(c.getColumnIndex("userNickname"));
String decryptedNickname = (nickName != null && !nickName.isEmpty())? cryptoUtils.decrypt(nickName) : "";
SWADNotification item = new SWADNotification(
c.getLong(c.getColumnIndex("id")),
c.getInt(c.getColumnIndex("eventCode")),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("eventType"))),
c.getLong(c.getColumnIndex("eventTime")),
decryptedNickname,
cryptoUtils.decrypt(c.getString(c.getColumnIndex("userSurname1"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("userSurname2"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("userFirstname"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("userPhoto"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("location"))),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("summary"))),
c.getInt(c.getColumnIndex("status")),
cryptoUtils.decrypt(c.getString(c.getColumnIndex("content"))),
Utils.parseIntBool(c.getInt(c.getColumnIndex("seenLocal"))),
Utils.parseIntBool(c.getInt(c.getColumnIndex("seenRemote")))
);
list.add(item);
}
c.close();
if (!list.isEmpty()) {
db.getSwadNotificationDao().insertSWADNotifications(list);
}
Log.d(TAG, tableName + " table migrated successfully");
}
private static void migrateTestConfigTableToRoom() {
String tableName = "tst_config";
String query = "SELECT * FROM " + tableName;
List<TestConfig> list = new ArrayList<>();
Log.d(TAG, "Migrating " + tableName + " table");
Cursor c = dbOld.rawQuery(query, null);
while (c.moveToNext()) {
TestConfig item = new TestConfig(
c.getLong(c.getColumnIndex("id")),
c.getInt(c.getColumnIndex("min")),
c.getInt(c.getColumnIndex("def")),
c.getInt(c.getColumnIndex("max")),
c.getString(c.getColumnIndex("feedback")),
c.getLong(c.getColumnIndex("editTime"))
);
list.add(item);
}
c.close();
if (!list.isEmpty()) {
db.getTestConfigDao().insertTestConfig(list);
}
Log.d(TAG, tableName + " table migrated successfully");
}
private static void migrateTesTagTableToRoom() {
String tableName = "tst_tags";
String query = "SELECT * FROM " + tableName;
List<TestTag> list = new ArrayList<>();
Log.d(TAG, "Migrating " + tableName + " table");
Cursor c = dbOld.rawQuery(query, null);
while (c.moveToNext()) {
TestTag item = new TestTag(
c.getLong(c.getColumnIndex("id")),
c.getString(c.getColumnIndex("tagTxt"))
);
list.add(item);
}
c.close();
if (!list.isEmpty()) {
db.getTestTagDao().insertTestTag(list);
}
Log.d(TAG, tableName + " table migrated successfully");
}
private static void migrateTestQuestionTableToRoom() {
String tableName = "tst_questions";
String query = "SELECT * FROM " + tableName + " tq" +
" INNER JOIN tst_questions_course tqc ON tq.id = tqc.qstCod";
List<TestQuestion> list = new ArrayList<>();
Log.d(TAG, "Migrating " + tableName + " table");
Cursor c = dbOld.rawQuery(query, null);
while (c.moveToNext()) {
TestQuestion item = new TestQuestion(
c.getLong(c.getColumnIndex("id")),
c.getLong(c.getColumnIndex("tqc.crsCod")),
c.getString(c.getColumnIndex("stem")),
c.getString(c.getColumnIndex("ansType")),
Utils.parseStringBool(c.getString(c.getColumnIndex("shuffle"))),
c.getString(c.getColumnIndex("feedback"))
);
list.add(item);
}
c.close();
if (!list.isEmpty()) {
db.getTestQuestionDao().insertTestQuestion(list);
}
Log.d(TAG, tableName + " table migrated successfully");
}
private static void migrateTesTagsQuestionsToRoom() {
String tableName = "tst_question_tags";
String query = "SELECT * FROM " + tableName;
List<TestTagsQuestions> list = new ArrayList<>();
Log.d(TAG, "Migrating " + tableName + " table");
Cursor c = dbOld.rawQuery(query, null);
while (c.moveToNext()) {
TestTagsQuestions item = new TestTagsQuestions(
c.getLong(c.getColumnIndex("qstCod")),
c.getLong(c.getColumnIndex("tagCod")),
c.getInt(c.getColumnIndex("tagInd"))
);
list.add(item);
}
c.close();
if (!list.isEmpty()) {
db.getTestTagsQuestionsDao().insertTestTagQuestion(list);
}
Log.d(TAG, tableName + " table migrated successfully");
}
private static void migrateTestAnswerTableToRoom() {
String tableName = "tst_answers";
String query = "SELECT * FROM " + tableName + " tqt" +
" INNER JOIN tst_question_answers tqa ON tqt.id = tqa.ansCod";
List<TestAnswer> list = new ArrayList<>();
Log.d(TAG, "Migrating " + tableName + " table");
Cursor c = dbOld.rawQuery(query, null);
while (c.moveToNext()) {
TestAnswer item = new TestAnswer(
c.getLong(c.getColumnIndex("id")),
c.getLong(c.getColumnIndex("tqa.qstCod")),
c.getInt(c.getColumnIndex("ansInd")),
Utils.parseIntBool(c.getInt(c.getColumnIndex("correct"))),
c.getString(c.getColumnIndex("answer")),
c.getString(c.getColumnIndex("answerFeedback"))
);
list.add(item);
}
c.close();
if (!list.isEmpty()) {
db.getTestAnswerDao().insertTestAnswer(list);
}
Log.d(TAG, tableName + " table migrated successfully");
}
}

View File

@ -19,21 +19,22 @@
package es.ugr.swad.swadroid.gui; package es.ugr.swad.swadroid.gui;
import static es.ugr.swad.swadroid.utils.NotificationUtils.SWADROID_CHANNEL_ID;
import android.app.Notification; import android.app.Notification;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.content.Context; import android.content.Context;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationCompat;
import es.ugr.swad.swadroid.utils.NotificationUtils; import es.ugr.swad.swadroid.utils.NotificationUtils;
import static es.ugr.swad.swadroid.utils.NotificationUtils.SWADROID_CHANNEL_ID;
/** /**
* Class for create notification alerts. * Class for create notification alerts.
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class AlertNotificationFactory { public class AlertNotificationFactory {
public static NotificationCompat.Builder createAlertNotificationBuilder(Context context, String contentTitle, String contentText, public static NotificationCompat.Builder createAlertNotificationBuilder(Context context, String contentTitle, String contentText,

View File

@ -23,7 +23,7 @@ import es.ugr.swad.swadroid.R;
/** /**
* Class for create dialogs. * Class for create dialogs.
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class DialogFactory { public class DialogFactory {
/** /**

View File

@ -12,7 +12,7 @@ import java.util.Map;
/** /**
* Manager for Font Awesome icons * Manager for Font Awesome icons
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class FontManager { public class FontManager {

View File

@ -35,7 +35,7 @@ import es.ugr.swad.swadroid.BuildConfig;
import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.R;
/** /**
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
* @author Helena Rodriguez Gijon <hrgijon@gmail.com> * @author Helena Rodriguez Gijon <hrgijon@gmail.com>
*/ */
public class ImageExpandableListAdapter extends SimpleExpandableListAdapter { public class ImageExpandableListAdapter extends SimpleExpandableListAdapter {

View File

@ -29,7 +29,7 @@ import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
/** /**
* Class for create images. * Class for create images.
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class ImageFactory { public class ImageFactory {
private static ImageLoader loader = ImageLoader.getInstance(); private static ImageLoader loader = ImageLoader.getInstance();

View File

@ -26,22 +26,23 @@ import android.content.Intent;
import android.content.pm.ApplicationInfo; import android.content.pm.ApplicationInfo;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log; import android.util.Log;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.widget.Toast; import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import es.ugr.swad.swadroid.Constants; import es.ugr.swad.swadroid.Constants;
import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.R;
import es.ugr.swad.swadroid.database.DataBaseHelper; import es.ugr.swad.swadroid.database.AppDatabase;
import es.ugr.swad.swadroid.preferences.Preferences; import es.ugr.swad.swadroid.preferences.Preferences;
import es.ugr.swad.swadroid.preferences.PreferencesActivity; import es.ugr.swad.swadroid.preferences.PreferencesActivity;
/** /**
* Superclass for add the options menu to all children classes of Activity * Superclass for add the options menu to all children classes of Activity
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
* @author Antonio Aguilera Malagon <aguilerin@gmail.com> * @author Antonio Aguilera Malagon <aguilerin@gmail.com>
* @author Helena Rodriguez Gijon <hrgijon@gmail.com> * @author Helena Rodriguez Gijon <hrgijon@gmail.com>
*/ */
@ -53,7 +54,7 @@ public class MenuActivity extends AppCompatActivity {
/** /**
* Database Helper. * Database Helper.
*/ */
protected static DataBaseHelper dbHelper; protected AppDatabase db;
/** /**
* Application debuggable flag * Application debuggable flag
*/ */
@ -65,24 +66,19 @@ public class MenuActivity extends AppCompatActivity {
/** /**
* Listener for dialog cancellation * Listener for dialog cancellation
*/ */
private OnClickListener cancelClickListener = new DialogInterface.OnClickListener() { private final OnClickListener cancelClickListener = (dialog, id) -> dialog.cancel();
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
};
/** /**
* Listener for clean database dialog * Listener for clean database dialog
*/ */
private OnClickListener positiveClickListener = new DialogInterface.OnClickListener() { private final OnClickListener positiveClickListener = (dialog, id) -> {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel(); dialog.cancel();
dbHelper.cleanTables(); db.clearAllTables();
AppDatabase.vacuumDb();
Preferences.setLastCourseSelected(0); Preferences.setLastCourseSelected(0);
DataBaseHelper.setDbCleaned(true); AppDatabase.setDbCleaned(true);
Toast.makeText(getApplicationContext(), R.string.cleanDatabaseMsg, Toast.LENGTH_LONG).show(); Toast.makeText(getApplicationContext(), R.string.cleanDatabaseMsg, Toast.LENGTH_LONG).show();
Log.i(Constants.APP_TAG, getString(R.string.cleanDatabaseMsg)); Log.i(Constants.APP_TAG, getString(R.string.cleanDatabaseMsg));
}
}; };
/** /**
@ -139,11 +135,7 @@ public class MenuActivity extends AppCompatActivity {
* @param message Error message to show. * @param message Error message to show.
*/ */
protected void error(String message, Exception ex) { protected void error(String message, Exception ex) {
DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() { DialogInterface.OnClickListener onClickListener = (dialog, id) -> finish();
public void onClick(DialogInterface dialog, int id) {
finish();
}
};
AlertDialog errorDialog = DialogFactory.createErrorDialog(this, TAG, message, ex, AlertDialog errorDialog = DialogFactory.createErrorDialog(this, TAG, message, ex,
isDebuggable, onClickListener); isDebuggable, onClickListener);
@ -203,7 +195,7 @@ public class MenuActivity extends AppCompatActivity {
prefs = new Preferences(this); prefs = new Preferences(this);
//Initialize database //Initialize database
dbHelper = new DataBaseHelper(this); db = AppDatabase.getAppDatabase(this);
getPackageManager().getApplicationInfo( getPackageManager().getApplicationInfo(
getPackageName(), 0); getPackageName(), 0);
isDebuggable = (ApplicationInfo.FLAG_DEBUGGABLE != 0); isDebuggable = (ApplicationInfo.FLAG_DEBUGGABLE != 0);
@ -217,7 +209,7 @@ public class MenuActivity extends AppCompatActivity {
*/ */
@Override @Override
protected void onPause() { protected void onPause() {
dbHelper.close(); AppDatabase.destroyInstance();
super.onPause(); super.onPause();
} }
@ -230,7 +222,7 @@ public class MenuActivity extends AppCompatActivity {
//Initialize database //Initialize database
try { try {
dbHelper = new DataBaseHelper(this); db = AppDatabase.getAppDatabase(this);
} catch (Exception ex) { } catch (Exception ex) {
error(ex.getMessage(), ex); error(ex.getMessage(), ex);
} }

View File

@ -26,23 +26,24 @@ import android.content.Intent;
import android.content.pm.ApplicationInfo; import android.content.pm.ApplicationInfo;
import android.net.Uri; import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log; import android.util.Log;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.widget.Toast; import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import es.ugr.swad.swadroid.Constants; import es.ugr.swad.swadroid.Constants;
import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.R;
import es.ugr.swad.swadroid.SWADMain; import es.ugr.swad.swadroid.SWADMain;
import es.ugr.swad.swadroid.database.DataBaseHelper; import es.ugr.swad.swadroid.database.AppDatabase;
import es.ugr.swad.swadroid.preferences.Preferences; import es.ugr.swad.swadroid.preferences.Preferences;
import es.ugr.swad.swadroid.preferences.PreferencesActivity; import es.ugr.swad.swadroid.preferences.PreferencesActivity;
/** /**
* Superclass for add the options menu to all children classes of ExpandableListActivity * Superclass for add the options menu to all children classes of ExpandableListActivity
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
* @author Antonio Aguilera Malagon <aguilerin@gmail.com> * @author Antonio Aguilera Malagon <aguilerin@gmail.com>
* @author Helena Rodriguez Gijon <hrgijon@gmail.com> * @author Helena Rodriguez Gijon <hrgijon@gmail.com>
*/ */
@ -54,7 +55,7 @@ public class MenuExpandableListActivity extends AppCompatActivity {
/** /**
* Database Helper. * Database Helper.
*/ */
protected static DataBaseHelper dbHelper; protected AppDatabase db;
/** /**
* Application debuggable flag * Application debuggable flag
*/ */
@ -70,25 +71,20 @@ public class MenuExpandableListActivity extends AppCompatActivity {
/** /**
* Listener for dialog cancellation * Listener for dialog cancellation
*/ */
private OnClickListener cancelClickListener = new DialogInterface.OnClickListener() { private final OnClickListener cancelClickListener = (dialog, id) -> dialog.cancel();
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
};
/** /**
* Listener for clean database dialog * Listener for clean database dialog
*/ */
private OnClickListener positiveClickListener = new DialogInterface.OnClickListener() { private final OnClickListener positiveClickListener = (dialog, id) -> {
public void onClick(DialogInterface dialog, int id) { db.clearAllTables();
dbHelper.cleanTables(); AppDatabase.vacuumDb();
Preferences.setLastCourseSelected(0); Preferences.setLastCourseSelected(0);
DataBaseHelper.setDbCleaned(true); AppDatabase.setDbCleaned(true);
Toast.makeText(getApplicationContext(), R.string.cleanDatabaseMsg, Toast.LENGTH_LONG).show(); Toast.makeText(getApplicationContext(), R.string.cleanDatabaseMsg, Toast.LENGTH_LONG).show();
if (isSWADMain) { if (isSWADMain) {
setMenuDbClean(); setMenuDbClean();
} }
Log.i(Constants.APP_TAG, getString(R.string.cleanDatabaseMsg)); Log.i(Constants.APP_TAG, getString(R.string.cleanDatabaseMsg));
}
}; };
/** /**
@ -125,7 +121,6 @@ public class MenuExpandableListActivity extends AppCompatActivity {
* Deletes all data from database * Deletes all data from database
*/ */
private void cleanDatabase() { private void cleanDatabase() {
AlertDialog cleanDBDialog = DialogFactory.createWarningDialog(this, AlertDialog cleanDBDialog = DialogFactory.createWarningDialog(this,
-1, -1,
R.string.areYouSure, R.string.areYouSure,
@ -146,11 +141,7 @@ public class MenuExpandableListActivity extends AppCompatActivity {
* @param message Error message to show. * @param message Error message to show.
*/ */
protected void error(String message, Exception ex) { protected void error(String message, Exception ex) {
DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() { DialogInterface.OnClickListener onClickListener = (dialog, id) -> finish();
public void onClick(DialogInterface dialog, int id) {
finish();
}
};
AlertDialog errorDialog = DialogFactory.createErrorDialog(this, TAG, message, ex, AlertDialog errorDialog = DialogFactory.createErrorDialog(this, TAG, message, ex,
isDebuggable, onClickListener); isDebuggable, onClickListener);
@ -218,7 +209,7 @@ public class MenuExpandableListActivity extends AppCompatActivity {
prefs = new Preferences(this); prefs = new Preferences(this);
//Initialize database //Initialize database
dbHelper = new DataBaseHelper(this); db = AppDatabase.getAppDatabase(this);
getPackageManager().getApplicationInfo( getPackageManager().getApplicationInfo(
getPackageName(), 0); getPackageName(), 0);
isDebuggable = (ApplicationInfo.FLAG_DEBUGGABLE != 0); isDebuggable = (ApplicationInfo.FLAG_DEBUGGABLE != 0);
@ -233,7 +224,7 @@ public class MenuExpandableListActivity extends AppCompatActivity {
*/ */
@Override @Override
protected void onPause() { protected void onPause() {
dbHelper.close(); AppDatabase.destroyInstance();
super.onPause(); super.onPause();
} }
@ -246,13 +237,13 @@ public class MenuExpandableListActivity extends AppCompatActivity {
//Initialize database //Initialize database
try { try {
dbHelper = new DataBaseHelper(this); db = AppDatabase.getAppDatabase(this);
} catch (Exception ex) { } catch (Exception ex) {
error(ex.getMessage(), ex); error(ex.getMessage(), ex);
} }
} }
protected void setMenuDbClean() { protected void setMenuDbClean() {
// No-op
} }
} }

View File

@ -13,7 +13,7 @@ import es.ugr.swad.swadroid.R;
/** /**
* Class for manage a progress screen * Class for manage a progress screen
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class ProgressScreen { public class ProgressScreen {
private View progressView; private View progressView;

View File

@ -24,7 +24,6 @@ import android.animation.ValueAnimator;
import android.annotation.TargetApi; import android.annotation.TargetApi;
import android.graphics.Rect; import android.graphics.Rect;
import android.os.Build; import android.os.Build;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.view.MotionEvent; import android.view.MotionEvent;
import android.view.VelocityTracker; import android.view.VelocityTracker;
import android.view.View; import android.view.View;
@ -33,6 +32,8 @@ import android.view.ViewGroup;
import android.widget.AbsListView; import android.widget.AbsListView;
import android.widget.ListView; import android.widget.ListView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;

View File

@ -35,7 +35,7 @@ import es.ugr.swad.swadroid.BuildConfig;
import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.R;
/** /**
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class TextExpandableListAdapter extends SimpleExpandableListAdapter { public class TextExpandableListAdapter extends SimpleExpandableListAdapter {
private final String NAME = "listText"; private final String NAME = "listText";

View File

@ -25,7 +25,7 @@ import android.webkit.WebViewClient;
/** /**
* Class for create WebViews * Class for create WebViews
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class WebViewFactory { public class WebViewFactory {
public static WebView getMathJaxWebView(WebView view) { public static WebView getMathJaxWebView(WebView view) {

View File

@ -18,16 +18,24 @@
*/ */
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.Index;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.util.Hashtable; import java.util.Hashtable;
import lombok.Data;
/** /**
* Class for store a course * Class for store a course
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
* @author Helena Rodriguez Gijon <hrgijon@gmail.com> * @author Helena Rodriguez Gijon <hrgijon@gmail.com>
*/ */
@Data
@Entity(indices = {@Index("shortName")})
public class Course extends Model { public class Course extends Model {
/** /**
* Course name * Course name
@ -35,10 +43,16 @@ public class Course extends Model {
private int userRole; private int userRole;
private String shortName; private String shortName;
private String fullName; private String fullName;
@Ignore
private static final PropertyInfo PI_id = new PropertyInfo(); private static final PropertyInfo PI_id = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userRole = new PropertyInfo(); private static final PropertyInfo PI_userRole = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_shortName = new PropertyInfo(); private static final PropertyInfo PI_shortName = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_fullName = new PropertyInfo(); private static final PropertyInfo PI_fullName = new PropertyInfo();
@Ignore
private static final PropertyInfo[] PI_PROP_ARRAY = private static final PropertyInfo[] PI_PROP_ARRAY =
{ {
PI_id, PI_id,
@ -47,11 +61,6 @@ public class Course extends Model {
PI_fullName PI_fullName
}; };
/**
* Constructor
*
* @param id Course identifier
*/
public Course(long id, int userRole, String shortName, String fullName) { public Course(long id, int userRole, String shortName, String fullName) {
super(id); super(id);
this.userRole = userRole; this.userRole = userRole;
@ -59,64 +68,6 @@ public class Course extends Model {
this.fullName = fullName; this.fullName = fullName;
} }
/**
* Gets user role inside the course
*
* @return user role (2 = student, 3 = teacher)
*/
public int getUserRole() {
return userRole;
}
/**
* Gets short course name
*
* @return Short course name
*/
public String getShortName() {
return shortName;
}
/**
* Sets short course name
*
* @param shortName short course name
*/
public void setShortName(String shortName) {
this.shortName = shortName;
}
/**
* Gets short course name
*
* @return Full course name
*/
public String getFullName() {
return fullName;
}
/**
* Sets short course name
*/
public void setFullName(String fullName) {
this.fullName = fullName;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + userRole;
result = prime * result + ((shortName == null) ? 0 : shortName.hashCode());
result = prime * result + ((fullName == null) ? 0 : fullName.hashCode());
return result;
}
/* (non-Javadoc) /* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#getProperty(int) * @see org.ksoap2.serialization.KvmSerializable#getProperty(int)
*/ */
@ -150,7 +101,7 @@ public class Course extends Model {
/* (non-Javadoc) /* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#getPropertyInfo(int, java.util.Hashtable, org.ksoap2.serialization.PropertyInfo) * @see org.ksoap2.serialization.KvmSerializable#getPropertyInfo(int, java.util.Hashtable, org.ksoap2.serialization.PropertyInfo)
*/ */
public void getPropertyInfo(int param, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo propertyInfo) { public void getPropertyInfo(int param, Hashtable arg1, PropertyInfo propertyInfo) {
switch (param) { switch (param) {
case 0: case 0:
propertyInfo.type = PropertyInfo.LONG_CLASS; propertyInfo.type = PropertyInfo.LONG_CLASS;
@ -193,19 +144,4 @@ public class Course extends Model {
} }
} }
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) return false;
Course other = (Course) obj;
return userRole == other.userRole && shortName.compareTo(other.getShortName()) == 0 && fullName.compareTo(other.getFullName()) == 0;
}
@Override
public String toString() {
return "Course{" +
"userRole=" + userRole +
", shortName='" + shortName + '\'' +
", fullName='" + fullName + '\'' +
"} " + super.toString();
}
} }

View File

@ -22,6 +22,11 @@ package es.ugr.swad.swadroid.model;
import android.text.TextUtils; import android.text.TextUtils;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.Ignore;
import androidx.room.Index;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.util.ArrayList; import java.util.ArrayList;
@ -30,12 +35,22 @@ import java.util.Collections;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.List; import java.util.List;
import lombok.Data;
/** /**
* Class for store a rollcall event * Class for store a rollcall event
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
@Data
@Entity(indices = {@Index("crsCod")},
foreignKeys = {
@ForeignKey(entity = Course.class,
parentColumns = "id",
childColumns = "crsCod",
onDelete = ForeignKey.CASCADE)})
public class Event extends Model { public class Event extends Model {
private long crsCod;
private boolean hidden; private boolean hidden;
private String userSurname1; private String userSurname1;
private String userSurname2; private String userSurname2;
@ -48,18 +63,32 @@ public class Event extends Model {
private String text; private String text;
private String groups; private String groups;
private String status; private String status;
@Ignore
private static final PropertyInfo PI_id = new PropertyInfo(); private static final PropertyInfo PI_id = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_hidden = new PropertyInfo(); private static final PropertyInfo PI_hidden = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userSurname1 = new PropertyInfo(); private static final PropertyInfo PI_userSurname1 = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userSurname2 = new PropertyInfo(); private static final PropertyInfo PI_userSurname2 = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userFirstName = new PropertyInfo(); private static final PropertyInfo PI_userFirstName = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userPhoto = new PropertyInfo(); private static final PropertyInfo PI_userPhoto = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_startTime = new PropertyInfo(); private static final PropertyInfo PI_startTime = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_endTime = new PropertyInfo(); private static final PropertyInfo PI_endTime = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_commentsTeachersVisible = new PropertyInfo(); private static final PropertyInfo PI_commentsTeachersVisible = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_title = new PropertyInfo(); private static final PropertyInfo PI_title = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_groups = new PropertyInfo(); private static final PropertyInfo PI_groups = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_status = new PropertyInfo(); private static final PropertyInfo PI_status = new PropertyInfo();
@Ignore
private static final PropertyInfo[] PI_PROP_ARRAY = private static final PropertyInfo[] PI_PROP_ARRAY =
{ {
PI_id, PI_id,
@ -76,14 +105,32 @@ public class Event extends Model {
PI_status PI_status
}; };
public Event(long crsCod, boolean hidden, String userSurname1, String userSurname2, String userFirstName, String userPhoto, long startTime, long endTime, boolean commentsTeachersVisible, String title, String text, String groups, String status) {
this.crsCod = crsCod;
this.hidden = hidden;
this.userSurname1 = userSurname1;
this.userSurname2 = userSurname2;
this.userFirstName = userFirstName;
this.userPhoto = userPhoto;
this.startTime = startTime;
this.endTime = endTime;
this.commentsTeachersVisible = commentsTeachersVisible;
this.title = title;
this.text = text;
this.groups = groups;
this.status = status;
}
/** /**
* Constructor with status * Constructor
*/ */
public Event(long attendanceEventCode, boolean hidden, String userSurname1, String userSurname2, public Event(long attendanceEventCode, long courseCode, boolean hidden, String userSurname1,
String userFirstName, String userPhoto, long startTime, long endTime, String userSurname2, String userFirstName, String userPhoto, long startTime,
boolean commentsTeachersVisible, String title, String text, String groups, long endTime, boolean commentsTeachersVisible, String title, String text, String groups,
String status) { String status) {
super(attendanceEventCode); super(attendanceEventCode);
this.crsCod = courseCode;
this.hidden = hidden; this.hidden = hidden;
this.userSurname1 = userSurname1; this.userSurname1 = userSurname1;
this.userSurname2 = userSurname2; this.userSurname2 = userSurname2;
@ -101,66 +148,14 @@ public class Event extends Model {
/** /**
* Constructor without status * Constructor without status
*/ */
public Event(long attendanceEventCode, boolean hidden, String userSurname1, String userSurname2, @Ignore
String userFirstName, String userPhoto, long startTime, long endTime, public Event(long attendanceEventCode, long courseCode, boolean hidden, String userSurname1,
boolean commentsTeachersVisible, String title, String text, String groups) { String userSurname2, String userFirstName, String userPhoto, long startTime,
super(attendanceEventCode); long endTime, boolean commentsTeachersVisible, String title, String text,
this.hidden = hidden; String groups) {
this.userSurname1 = userSurname1;
this.userSurname2 = userSurname2;
this.userFirstName = userFirstName;
this.userPhoto = userPhoto;
this.startTime = startTime;
this.endTime = endTime;
this.commentsTeachersVisible = commentsTeachersVisible;
this.title = title;
this.text = text;
this.groups = groups;
this.status = "OK";
}
public boolean isHidden() { this(attendanceEventCode, courseCode, hidden, userSurname1, userSurname2, userFirstName, userPhoto,
return hidden; startTime, endTime, commentsTeachersVisible, title, text, groups, "OK");
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
public String getUserSurname1() {
return userSurname1;
}
public void setUserSurname1(String userSurname1) {
this.userSurname1 = userSurname1;
}
public String getUserSurname2() {
return userSurname2;
}
public void setUserSurname2(String userSurname2) {
this.userSurname2 = userSurname2;
}
public String getUserFirstName() {
return userFirstName;
}
public void setUserFirstName(String userFirstName) {
this.userFirstName = userFirstName;
}
public String getUserPhoto() {
return userPhoto;
}
public void setUserPhoto(String userPhoto) {
this.userPhoto = userPhoto;
}
public long getStartTime() {
return startTime;
} }
public Calendar getStartTimeCalendar() { public Calendar getStartTimeCalendar() {
@ -169,56 +164,12 @@ public class Event extends Model {
return calendar; return calendar;
} }
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public long getEndTime() {
return endTime;
}
public Calendar getEndTimeCalendar() { public Calendar getEndTimeCalendar() {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(endTime * 1000L); calendar.setTimeInMillis(endTime * 1000L);
return calendar; return calendar;
} }
public void setEndTime(long endTime) {
this.endTime = endTime;
}
public boolean isCommentsTeachersVisible() {
return commentsTeachersVisible;
}
public void setCommentsTeachersVisible(boolean commentsTeachersVisible) {
this.commentsTeachersVisible = commentsTeachersVisible;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getGroups() {
return groups;
}
public void setGroups(String groups) {
this.groups = groups;
}
public List<String> getGroupsList() { public List<String> getGroupsList() {
return new ArrayList(Collections.singletonList(groups)); return new ArrayList(Collections.singletonList(groups));
} }
@ -227,14 +178,6 @@ public class Event extends Model {
this.groups = TextUtils.join(",", groups); this.groups = TextUtils.join(",", groups);
} }
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
/* (non-Javadoc) /* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#getProperty(int) * @see org.ksoap2.serialization.KvmSerializable#getProperty(int)
*/ */
@ -399,21 +342,4 @@ public class Event extends Model {
} }
} }
@Override
public String toString() {
return "Event{" +
"hidden=" + hidden +
", userSurname1='" + userSurname1 + '\'' +
", userSurname2='" + userSurname2 + '\'' +
", userFirstName='" + userFirstName + '\'' +
", userPhoto='" + userPhoto + '\'' +
", startTime=" + startTime +
", endTime=" + endTime +
", commentsTeachersVisible=" + commentsTeachersVisible +
", title='" + title + '\'' +
", text='" + text + '\'' +
", groups='" + groups + '\'' +
", status='" + status + '\'' +
"} " + super.toString();
}
} }

View File

@ -19,17 +19,29 @@
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.Index;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.io.Serializable;
import java.util.Hashtable; import java.util.Hashtable;
import lombok.Data;
/** /**
* User data. * User data.
* *
* @author Rubén Martín Hidalgo * @author Rubén Martín Hidalgo
*/ */
public class FrequentUser extends Model implements Serializable{ @Data
@Entity(indices = {@Index("idUser")},
foreignKeys = {
@ForeignKey(entity = User.class,
parentColumns = "id",
childColumns = "idUser",
onDelete = ForeignKey.CASCADE)})
public class FrequentUser extends Model {
/** /**
* Sender identifier. * Sender identifier.
*/ */
@ -80,7 +92,8 @@ public class FrequentUser extends Model implements Serializable{
* @param selectedCheckbox Is a receiver?. * @param selectedCheckbox Is a receiver?.
* @param score Score of frequent recipient * @param score Score of frequent recipient
*/ */
public FrequentUser(String idUser, String userNickname, String userSurname1, String userSurname2, String userFirstname, String userPhoto, int userCode, boolean selectedCheckbox, double score) { public FrequentUser(long id, String idUser, String userNickname, String userSurname1, String userSurname2, String userFirstname, String userPhoto, int userCode, boolean selectedCheckbox, double score) {
super(id);
this.idUser = idUser; this.idUser = idUser;
this.userNickname = userNickname; this.userNickname = userNickname;
this.userSurname1 = userSurname1; this.userSurname1 = userSurname1;
@ -92,168 +105,6 @@ public class FrequentUser extends Model implements Serializable{
this.score = score; this.score = score;
} }
/**
* Gets sender identifier.
*
* @return Sender identifier.
*/
public String getidUser() {
return this.idUser;
}
/**
* Sets sender identifier.
*
* @param idUser Sender identifier.
*/
public void setIdUser(String idUser) {
this.idUser = idUser;
}
/**
* Gets user name.
*
* @return User name.
*/
public String getUserFirstname() {
return userFirstname;
}
/**
* Sets user name.
*
* @param userFirstname User name.
*/
public void setUserFirstname(String userFirstname) {
this.userFirstname = userFirstname;
}
/**
* Gets user identifier.
*
* @return User identifier.
*/
public String getUserNickname() {
return userNickname;
}
/**
* Sets user identifier.
*
* @param userNickname User identifier.
*/
public void setUserNickname(String userNickname) {
this.userNickname = userNickname;
}
/**
* Gets user first surname.
*
* @return User first surname.
*/
public String getUserSurname1() {
return userSurname1;
}
/**
* Sets user first surname.
*
* @param userSurname1 User first surname.
*/
public void setUserSurname1(String userSurname1) {
this.userSurname1 = userSurname1;
}
/**
* Gets user last surname.
*
* @return User last surname.
*/
public String getUserSurname2() {
return userSurname2;
}
/**
* Sets user last surname.
*
* @param userSurname2 User last surname.
*/
public void setUserSurname2(String userSurname2) {
this.userSurname2 = userSurname2;
}
/**
* Gets Full path where user's picture is stored.
*
* @return the userPhoto
*/
public String getUserPhoto() {
return userPhoto;
}
/**
* Sets Full path where user's picture is stored.
*
* @param userPhoto the userPhoto to set
*/
public void setUserPhoto(String userPhoto) {
this.userPhoto = userPhoto;
}
/**
* Gets userCode.
*
* @return the userPhoto
*/
public int getUserCode() {
return userCode;
}
/**
* Sets userCode.
*
* @param userCode
*/
public void setUserCode(int userCode) {
this.userCode = userCode;
}
/**
* Get if checkbox is selected.
*
* @return if checkbox is selected (true / false)
*/
public boolean getCheckbox() {
return selectedCheckbox;
}
/**
* Sets Full path where user's picture is stored.
*
* @param selected the checkbox is selected or not
*/
public void setCheckbox(boolean selected){
this.selectedCheckbox = selected;
}
/**
* Get score of frequent recipient.
*
* @return score
*/
public double getScore() {
return score;
}
/**
* Set score of frequent recipient.
*
* @param score
*/
public void setScore(double score){
this.score = score;
}
@Override @Override
public Object getProperty(int index) { public Object getProperty(int index) {
return null; return null;

View File

@ -1,15 +1,30 @@
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.Ignore;
import androidx.room.Index;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.util.Hashtable; import java.util.Hashtable;
import lombok.Data;
/** /**
* Class for store a group. A group is related to a course and to a group type * Class for store a group. A group is related to a course and to a group type
* *
* @author Helena Rodriguez Gijon <hrgijon@gmail.com> * @author Helena Rodriguez Gijon <hrgijon@gmail.com>
* @author Antonio Aguilera Malagon <aguilerin@gmail.com> * @author Antonio Aguilera Malagon <aguilerin@gmail.com>
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
@Data
@Entity(indices = {@Index("groupTypeCode"), @Index("crsCod")},
foreignKeys = {
@ForeignKey(entity = Course.class,
parentColumns = "id",
childColumns = "crsCod",
onDelete = ForeignKey.CASCADE)})
public class Group extends Model { public class Group extends Model {
/** /**
* Group name. * Group name.
@ -19,6 +34,10 @@ public class Group extends Model {
* Group type code to which the group belongs * Group type code to which the group belongs
*/ */
private long groupTypeCode = -1; private long groupTypeCode = -1;
/**
* Group course code to which the group belongs
*/
private long crsCod = -1;
/** /**
* Maximum number of students allowed in this group * Maximum number of students allowed in this group
*/ */
@ -40,15 +59,24 @@ public class Group extends Model {
*/ */
private int member; private int member;
@Ignore
private static final PropertyInfo PI_id = new PropertyInfo(); private static final PropertyInfo PI_id = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_groupName = new PropertyInfo(); private static final PropertyInfo PI_groupName = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_maxStudents = new PropertyInfo(); private static final PropertyInfo PI_maxStudents = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_students = new PropertyInfo(); private static final PropertyInfo PI_students = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_open = new PropertyInfo(); private static final PropertyInfo PI_open = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_fileZones = new PropertyInfo(); private static final PropertyInfo PI_fileZones = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_member = new PropertyInfo(); private static final PropertyInfo PI_member = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_groupTypeCode = new PropertyInfo(); private static final PropertyInfo PI_groupTypeCode = new PropertyInfo();
@Ignore
private static final PropertyInfo[] PI_PROP_ARRAY = { private static final PropertyInfo[] PI_PROP_ARRAY = {
PI_id, PI_id,
PI_groupName, PI_groupName,
@ -60,25 +88,15 @@ public class Group extends Model {
PI_member PI_member
}; };
/** public Group(long id, String groupName, long groupTypeCode, long crsCod, int maxStudents, int students, int open, int fileZones, int member) {
* Constructor.
*
* @param id Group code.
* @param groupName Group name.
* @param maxStudents Maximum number of students allowed in this group
* @param students Current number of students that belong to this group
* @param open Indicates whether the enrollment to this group is allowed or not
* @param fileZones Indicates whether the group has an area of documents related to or not
* @param member Indicates if the logged user is a member of this group
*/
public Group(long id, String groupName, long groupTypeCode, int maxStudents, int open, int students, int fileZones, int member) {
super(id); super(id);
this.groupName = groupName; this.groupName = groupName;
this.groupTypeCode = groupTypeCode;
this.crsCod = crsCod;
this.maxStudents = maxStudents; this.maxStudents = maxStudents;
this.students = students; this.students = students;
this.open = open; this.open = open;
this.fileZones = fileZones; this.fileZones = fileZones;
this.groupTypeCode = groupTypeCode;
this.member = member; this.member = member;
} }
@ -122,7 +140,7 @@ public class Group extends Model {
} }
@Override @Override
public void getPropertyInfo(int param, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo propertyInfo) { public void getPropertyInfo(int param, Hashtable arg1, PropertyInfo propertyInfo) {
switch (param) { switch (param) {
case 0: case 0:
propertyInfo.type = PropertyInfo.LONG_CLASS; propertyInfo.type = PropertyInfo.LONG_CLASS;
@ -190,108 +208,6 @@ public class Group extends Model {
} }
/**
* Gets group name
*
* @return group name
*/
public String getGroupName() {
return groupName;
}
/**
* Gets group type code to which the group belongs
*
* @return groupTypeCode code
*/
public long getGroupTypeCode() {
return groupTypeCode;
}
/**
* Gets maximum number of students allowed in this group
*
* @return -1 if there is not a limit of students for this group, maximum number allowed otherwise
*/
public int getMaxStudents() {
return maxStudents;
}
/**
* Indicates if there is a limit of students for this group
*
* @return true if there is not a limit of students for this group, false otherwise
*/
public boolean existsMaxStudents() {
return maxStudents != -1;
}
/**
* Gets current student number enrolled in this group
*
* @return current number of students enrolled in this group over 0 and, in case there is a limit of students, maximum students allowed
*/
public int getCurrentStudents() {
return students;
}
/**
* Gets the number of available vacancies in this group
*
* @return -1 if there is not a limit of students for this group
* number of available vacancies currently otherwise
*/
public int getVacancies() {
if (maxStudents == -1) return -1;
else
return maxStudents - students;
}
/**
* Indicates if the enrollment in this group is already allowed
*
* @return true if the enrollment is already allowed
* false otherwise
*/
public boolean isOpen() {
return open != 0;
}
/**
* Indicates if the enrollment in this group is already allowed
*
* @return not 0 if the enrollment is already allowed
* 0 otherwise
*/
public int getOpen() {
return open;
}
public void setOpen(int open) {
this.open = open;
}
/**
* Indicates if the group has an area of documents and of shared documents related to or not
*
* @return true if the area of documents exits
* false otherwise
*/
public boolean exitsDocumentsArea() {
return fileZones != 0;
}
/**
* Indicates if the group has an area of documents and of shared documents related to or not
*
* @return not 0 if the area of documents exits
* false otherwise
*/
public int getDocumentsArea() {
return fileZones;
}
/** /**
* Indicates if the logged user is a member of this group * Indicates if the logged user is a member of this group
* *
@ -302,22 +218,6 @@ public class Group extends Model {
return member != 0; return member != 0;
} }
/**
* Indicates if the logged user is a member of this group
*
* @return not 0 if the logged user is a member of this group
* 0 otherwise
*/
public int getMember() {
return member;
}
/**
* Set that the user belongs to this group or not
*/
public void setMember(int member) {
this.member = member;
}
//TODO relate Group to Group Type //TODO relate Group to Group Type
/* public String getGroupCompleteName(){ /* public String getGroupCompleteName(){
@ -326,53 +226,4 @@ public class Group extends Model {
*/ */
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = (int) (prime * result + this.getId());
result = prime * result
+ ((groupName == null) ? 0 : groupName.hashCode());
result = (int) (prime * result + groupTypeCode);
result = prime * result + maxStudents;
result = prime * result + students;
result = prime * result + open;
result = prime * result + fileZones;
result = prime * result + member;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Group other = (Group) obj;
if (getId() != other.getId())
return false;
if (groupName == null) {
if (other.groupName != null)
return false;
} else if (!groupName.equals(other.groupName))
return false;
if (groupTypeCode != other.groupTypeCode)
return false;
return maxStudents == other.maxStudents && students == other.students && open == other.open && fileZones == other.fileZones && member == other.member;
}
@Override
public String toString() {
return "Group{" +
"groupName='" + groupName + '\'' +
", groupTypeCode=" + groupTypeCode +
", maxStudents=" + maxStudents +
", students=" + students +
", open=" + open +
", fileZones=" + fileZones +
", member=" + member +
"} " + super.toString();
}
} }

View File

@ -1,14 +1,27 @@
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.Ignore;
import androidx.room.Index;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.util.Hashtable; import java.util.Hashtable;
import lombok.Data;
/** /**
* Class to store a Group Type. A group type is related to a course and to multiple groups * Class to store a Group Type. A group type is related to a course and to multiple groups
* * @author Helena Rodriguez Gijon <hrgijon@gmail.com> * * @author Helena Rodriguez Gijon <hrgijon@gmail.com>
*/ */
@Data
@Entity(indices = {@Index("courseCode"), @Index("groupTypeName")},
foreignKeys = {
@ForeignKey(entity = Course.class,
parentColumns = "id",
childColumns = "courseCode",
onDelete = ForeignKey.CASCADE)})
public class GroupType extends Model { public class GroupType extends Model {
/** /**
@ -16,9 +29,9 @@ public class GroupType extends Model {
*/ */
private String groupTypeName; private String groupTypeName;
/** /**
* course code to which the request is related * Course code to which the request is related
*/ */
private long courseCode = -1; private long courseCode;
/** /**
* Indicates if the enrollment in this group is mandatory or not * Indicates if the enrollment in this group is mandatory or not
*/ */
@ -33,13 +46,20 @@ public class GroupType extends Model {
*/ */
private long openTime; private long openTime;
@Ignore
private static final PropertyInfo PI_id = new PropertyInfo(); private static final PropertyInfo PI_id = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_groupTypeName = new PropertyInfo(); private static final PropertyInfo PI_groupTypeName = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_courseCode = new PropertyInfo(); private static final PropertyInfo PI_courseCode = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_mandatory = new PropertyInfo(); private static final PropertyInfo PI_mandatory = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_multiple = new PropertyInfo(); private static final PropertyInfo PI_multiple = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_openTime = new PropertyInfo(); private static final PropertyInfo PI_openTime = new PropertyInfo();
@Ignore
private static final PropertyInfo[] PI_PROP_ARRAY = { private static final PropertyInfo[] PI_PROP_ARRAY = {
PI_id, PI_id,
PI_groupTypeName, PI_groupTypeName,
@ -49,14 +69,6 @@ public class GroupType extends Model {
PI_openTime PI_openTime
}; };
/**
* Constructor.
*
* @param id Group code.
* @param groupTypeName Group type name.
* @param mandatory Indicates if the enrollment in this group is mandatory or not
* @param multiple Indicates if a multiple enrollment is allowed
*/
public GroupType(long id, String groupTypeName, long courseCode, int mandatory, int multiple, long openTime) { public GroupType(long id, String groupTypeName, long courseCode, int mandatory, int multiple, long openTime) {
super(id); super(id);
this.groupTypeName = groupTypeName; this.groupTypeName = groupTypeName;
@ -99,7 +111,7 @@ public class GroupType extends Model {
} }
@Override @Override
public void getPropertyInfo(int param, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo propertyInfo) { public void getPropertyInfo(int param, Hashtable arg1, PropertyInfo propertyInfo) {
switch (param) { switch (param) {
case 0: case 0:
propertyInfo.type = PropertyInfo.LONG_CLASS; propertyInfo.type = PropertyInfo.LONG_CLASS;
@ -153,81 +165,4 @@ public class GroupType extends Model {
} }
/**
* Gets group type name
*
* @return group type name
*/
public String getGroupTypeName() {
return groupTypeName;
}
/**
* Indicates if the enrollment in this group is mandatory or not
*
* @return true if the enrollment is mandatory, false otherwise
*/
public boolean isMandatory() {
return mandatory != 0;
}
/**
* Indicates if a multiple enrollment is allowed
*
* @return true if a multiple enrollment is allowed , false otherwise
*/
public boolean isMultiple() {
return multiple != 0;
}
/**
* Gets course code to which the group type is related to
*
* @return courseCode
* -1 in case the group type is not related to any course
*/
public long getCourseCode() {
return courseCode;
}
/**
* Indicates if the enrollment is mandatory
*
* @return 0 - if the inscription is not mandatory
* not 0 otherwise
*/
public int getMandatory() {
return mandatory;
}
/**
* Indicates if a multiple enrollment is allowed
*
* @return 0 - if the inscription is not multiple
* not 0 otherwise
*/
public int getMultiple() {
return multiple;
}
/**
* Gets the date when the groups of this kind will be automatically opened, in case, it exits
*
* @return 0 if there is not a date when the groups of this kind will be automatically opened
* otherwise date in unix format (see http://en.wikipedia.org/wiki/Unix_time)
*/
public long getOpenTime() {
return openTime;
}
@Override
public String toString() {
return "GroupType{" +
"groupTypeName='" + groupTypeName + '\'' +
", courseCode=" + courseCode +
", mandatory=" + mandatory +
", multiple=" + multiple +
", openTime=" + openTime +
"} " + super.toString();
}
} }

View File

@ -0,0 +1,42 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.model;
import androidx.room.Embedded;
import androidx.room.Relation;
import java.util.List;
import lombok.Data;
/**
* Groups related to a course.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>.
*/
@Data
public class GroupsCourse {
@Embedded
public Course course;
@Relation(
parentColumn = "id",
entityColumn = "crsCod"
)
public List<Group> groups;
}

View File

@ -0,0 +1,42 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.model;
import androidx.room.Embedded;
import androidx.room.Relation;
import java.util.List;
import lombok.Data;
/**
* Group types related to a group.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>.
*/
@Data
public class GroupsGroupType {
@Embedded
public GroupType groupType;
@Relation(
parentColumn = "id",
entityColumn = "groupTypeCode"
)
public List<Group> groups;
}

View File

@ -1,10 +1,17 @@
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import androidx.room.Entity;
import androidx.room.Ignore;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.io.Serializable; import java.io.Serializable;
import java.util.Hashtable; import java.util.Hashtable;
import lombok.Data;
@Data
@Entity
public class Location extends Model implements Serializable { public class Location extends Model implements Serializable {
protected int institutionCode; protected int institutionCode;
@ -33,20 +40,35 @@ public class Location extends Model implements Serializable {
protected String roomFullName; protected String roomFullName;
@Ignore
protected static final PropertyInfo PI_id = new PropertyInfo(); protected static final PropertyInfo PI_id = new PropertyInfo();
@Ignore
protected static final PropertyInfo PI_institutionCode = new PropertyInfo(); protected static final PropertyInfo PI_institutionCode = new PropertyInfo();
@Ignore
protected static final PropertyInfo PI_institutionShortName = new PropertyInfo(); protected static final PropertyInfo PI_institutionShortName = new PropertyInfo();
@Ignore
protected static final PropertyInfo PI_institutionFullName = new PropertyInfo(); protected static final PropertyInfo PI_institutionFullName = new PropertyInfo();
@Ignore
protected static final PropertyInfo PI_centerCode = new PropertyInfo(); protected static final PropertyInfo PI_centerCode = new PropertyInfo();
@Ignore
protected static final PropertyInfo PI_centerShortName = new PropertyInfo(); protected static final PropertyInfo PI_centerShortName = new PropertyInfo();
@Ignore
protected static final PropertyInfo PI_centerFullName = new PropertyInfo(); protected static final PropertyInfo PI_centerFullName = new PropertyInfo();
@Ignore
protected static final PropertyInfo PI_buildingCode = new PropertyInfo(); protected static final PropertyInfo PI_buildingCode = new PropertyInfo();
@Ignore
protected static final PropertyInfo PI_buildingShortName = new PropertyInfo(); protected static final PropertyInfo PI_buildingShortName = new PropertyInfo();
@Ignore
protected static final PropertyInfo PI_buildingFullName = new PropertyInfo(); protected static final PropertyInfo PI_buildingFullName = new PropertyInfo();
@Ignore
protected static final PropertyInfo PI_floor = new PropertyInfo(); protected static final PropertyInfo PI_floor = new PropertyInfo();
@Ignore
protected static final PropertyInfo PI_roomCode = new PropertyInfo(); protected static final PropertyInfo PI_roomCode = new PropertyInfo();
@Ignore
protected static final PropertyInfo PI_roomShortName = new PropertyInfo(); protected static final PropertyInfo PI_roomShortName = new PropertyInfo();
@Ignore
protected static final PropertyInfo PI_roomFullName = new PropertyInfo(); protected static final PropertyInfo PI_roomFullName = new PropertyInfo();
@Ignore
protected static PropertyInfo[] PI_PROP_ARRAY = protected static PropertyInfo[] PI_PROP_ARRAY =
{ {
PI_id, PI_id,
@ -81,110 +103,6 @@ public class Location extends Model implements Serializable {
this.roomFullName = roomFullName; this.roomFullName = roomFullName;
} }
public int getInstitutionCode() {
return institutionCode;
}
public void setInstitutionCode(int institutionCode) {
this.institutionCode = institutionCode;
}
public String getInstitutionShortName() {
return institutionShortName;
}
public void setInstitutionShortName(String institutionShortName) {
this.institutionShortName = institutionShortName;
}
public String getInstitutionFullName() {
return institutionFullName;
}
public void setInstitutionFullName(String institutionFullName) {
this.institutionFullName = institutionFullName;
}
public int getCenterCode() {
return centerCode;
}
public void setCenterCode(int centerCode) {
this.centerCode = centerCode;
}
public String getCenterShortName() {
return centerShortName;
}
public void setCenterShortName(String centerShortName) {
this.centerShortName = centerShortName;
}
public String getCenterFullName() {
return centerFullName;
}
public void setCenterFullName(String centerFullName) {
this.centerFullName = centerFullName;
}
public int getBuildingCode() {
return buildingCode;
}
public void setBuildingCode(int buildingCode) {
this.buildingCode = buildingCode;
}
public String getBuildingShortName() {
return buildingShortName;
}
public void setBuildingShortName(String buildingShortName) {
this.buildingShortName = buildingShortName;
}
public String getBuildingFullName() {
return buildingFullName;
}
public void setBuildingFullName(String buildingFullName) {
this.buildingFullName = buildingFullName;
}
public int getFloor() {
return floor;
}
public void setFloor(int floor) {
this.floor = floor;
}
public int getRoomCode() {
return roomCode;
}
public void setRoomCode(int roomCode) {
this.roomCode = roomCode;
}
public String getRoomShortName() {
return roomShortName;
}
public void setRoomShortName(String roomShortName) {
this.roomShortName = roomShortName;
}
public String getRoomFullName() {
return roomFullName;
}
public void setRoomFullName(String roomFullName) {
this.roomFullName = roomFullName;
}
@Override @Override
public Object getProperty(int param) { public Object getProperty(int param) {
Object object = null; Object object = null;
@ -350,22 +268,4 @@ public class Location extends Model implements Serializable {
} }
} }
@Override
public String toString() {
return "Location{" +
"institutionCode=" + institutionCode +
", institutionShortName='" + institutionShortName + '\'' +
", institutionFullName='" + institutionFullName + '\'' +
", centerCode=" + centerCode +
", centerShortName='" + centerShortName + '\'' +
", centerFullName='" + centerFullName + '\'' +
", buildingCode=" + buildingCode +
", buildingShortName='" + buildingShortName + '\'' +
", buildingFullName='" + buildingFullName + '\'' +
", floor=" + floor +
", roomCode=" + roomCode +
", roomShortName='" + roomShortName + '\'' +
", roomFullName='" + roomFullName + '\'' +
'}';
}
} }

View File

@ -1,10 +1,16 @@
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import androidx.room.Entity;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.io.Serializable; import java.io.Serializable;
import java.util.Hashtable; import java.util.Hashtable;
import lombok.Data;
@Data
@Entity
public class LocationTimeStamp extends Location implements Serializable { public class LocationTimeStamp extends Location implements Serializable {
private int checkInTime; private int checkInTime;
@ -14,14 +20,6 @@ public class LocationTimeStamp extends Location implements Serializable {
this.checkInTime = checkInTime; this.checkInTime = checkInTime;
} }
public int getCheckInTime() {
return checkInTime;
}
public void setCheckInTime(int checkInTime) {
this.checkInTime = checkInTime;
}
@Override @Override
public Object getProperty(int param) { public Object getProperty(int param) {
Object object; Object object;
@ -57,23 +55,4 @@ public class LocationTimeStamp extends Location implements Serializable {
} }
} }
@Override
public String toString() {
return "LocationTimeStamp{" +
"institutionCode=" + institutionCode +
", institutionShortName='" + institutionShortName + '\'' +
", institutionFullName='" + institutionFullName + '\'' +
", centerCode=" + centerCode +
", centerShortName='" + centerShortName + '\'' +
", centerFullName='" + centerFullName + '\'' +
", buildingCode=" + buildingCode +
", buildingShortName='" + buildingShortName + '\'' +
", buildingFullName='" + buildingFullName + '\'' +
", floor=" + floor +
", roomCode=" + roomCode +
", roomShortName='" + roomShortName + '\'' +
", roomFullName='" + roomFullName + '\'' +
", checkInTime'" + checkInTime + '\'' +
'}';
}
} }

View File

@ -1,12 +1,13 @@
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import es.ugr.swad.swadroid.Constants; import lombok.Data;
/** /**
* Login data. * Login data.
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
@Data
public class LoginInfo { public class LoginInfo {
/** /**
* User logged flag * User logged flag
@ -32,94 +33,4 @@ public class LoginInfo {
this.currentUserRole = -1; this.currentUserRole = -1;
} }
public LoginInfo(boolean logged, User loggedUser, long lastLoginTime, int currentUserRole) {
this.logged = logged;
this.loggedUser = loggedUser;
this.lastLoginTime = lastLoginTime;
this.currentUserRole = currentUserRole;
}
/**
* Checks if user is already logged on SWAD
*
* @return User logged flag
*/
public boolean isLogged() {
return logged;
}
/**
* Sets user logged flag
*
* @param logged User logged flag
*/
public void setLogged(boolean logged) {
this.logged = logged;
}
/**
* Gets the user logged on SWAD
*/
public User getLoggedUser() {
return loggedUser;
}
/**
* Sets the user logged on SWAD
*/
public void setLoggedUser(User loggedUser) {
this.loggedUser = loggedUser;
}
/**
* Gets the last synchronization time
*
* @return The last synchronization time
*/
public long getLastLoginTime() {
return lastLoginTime;
}
/**
* Sets the last synchronization time
*
* @param lastLoginTime The last synchronization time
*/
public void setLastLoginTime(long lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
/**
* Gets the role of the logged user in the current selected course
*
* @return -1 if the user role has not been fixed,
* 0 if the user role is unknown
* 2 (STUDENT_TYPE_CODE) if the user is a student
* 3 (TEACHER_TYPE_CODE) if the user is a teacher
*/
public int getCurrentUserRole() {
return currentUserRole;
}
/**
* Sets user role in the current selected course
*
* @param userRole Role of the user: 0- unknown STUDENT_TYPE_CODE - student TEACHER_TYPE_CODE - teacher
*/
public void setCurrentUserRole(int userRole) {
if (userRole == 0 || userRole == Constants.TEACHER_TYPE_CODE || userRole == Constants.STUDENT_TYPE_CODE)
currentUserRole = userRole;
else
currentUserRole = -1;
}
@Override
public String toString() {
return "LoginInfo{" +
"logged=" + logged +
", loggedUser=" + loggedUser +
", lastLoginTime=" + lastLoginTime +
", currentUserRole=" + currentUserRole +
'}';
}
} }

View File

@ -18,75 +18,29 @@
*/ */
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import androidx.room.PrimaryKey;
import org.ksoap2.serialization.KvmSerializable; import org.ksoap2.serialization.KvmSerializable;
import lombok.Data;
/** /**
* Superclass for encapsulate common behavior of all Models. * Superclass for encapsulate common behavior of all Models.
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
@Data
public abstract class Model implements KvmSerializable { public abstract class Model implements KvmSerializable {
/** /**
* Model identifier * Model identifier
*/ */
private long id; @PrimaryKey
protected long id;
Model(long id) {
super();
this.id = id;
}
protected Model() { protected Model() {
} }
/** protected Model(long id) {
* Gets model identifier
*
* @return Model identifier
*/
public long getId() {
return id;
}
/**
* Sets model identifier
*
* @param id Model identifier
*/
void setId(long id) {
this.id = id; this.id = id;
} }
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Model other = (Model) obj;
return id == other.id;
}
@Override
public String toString() {
return "Model{" +
"id=" + id +
'}';
}
} }

View File

@ -1,100 +0,0 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.model;
/**
* Class for manage a pair of values
*
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*/
public class Pair<FIRST, SECOND> {
/**
* First value
*/
private FIRST first;
/**
* Second value
*/
private SECOND second;
/**
* Constructor
*
* @param f First value
* @param s Second value
*/
public Pair(FIRST f, SECOND s) {
first = f;
second = s;
}
/**
* Gets first value
*
* @return First value
*/
public FIRST getFirst() {
return first;
}
/**
* Gets second value
*
* @return Second value
*/
public SECOND getSecond() {
return second;
}
/**
* Sets first value
* param first First value
*/
public void setFirst(FIRST first) {
this.first = first;
}
/**
* Sets second value
* param second Second value
*/
public void setSecond(SECOND second) {
this.second = second;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((first == null) ? 0 : first.hashCode());
result = prime * result + ((second == null) ? 0 : second.hashCode());
return result;
}
@Override
public String toString() {
return "Pair{" +
"first=" + first +
", second=" + second +
'}';
}
}

View File

@ -1,151 +0,0 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.model;
import org.ksoap2.serialization.PropertyInfo;
import java.util.Hashtable;
/**
* Specific Pair class for database tables
*
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*/
public class PairTable<FIRST, SECOND> extends Model {
/**
* Pair of values
*/
private final Pair<FIRST, SECOND> values;
/**
* Table who owns the pair of values
*/
private String table;
/**
* Constructor
*
* @param table Table who owns the pair of values
* @param first First value
* @param second Second value
*/
public PairTable(String table, FIRST first, SECOND second) {
super(0);
this.values = new Pair<>(first, second);
this.table = table;
}
/**
* Gets the pair of values
*
* @return Pair of values
*/
public Pair<FIRST, SECOND> getValues() {
return values;
}
/**
* Gets first value
*
* @return First value
*/
public FIRST getFirst() {
return this.values.getFirst();
}
/**
* Gets second value
*
* @return Second value
*/
public SECOND getSecond() {
return this.values.getSecond();
}
/**
* Sets first value
* param first First value
*/
public void setFirst(FIRST first) {
this.values.setFirst(first);
}
/**
* Sets second value
* param second Second value
*/
public void setSecond(SECOND second) {
this.values.setSecond(second);
}
/**
* Gets the table who owns the pair of values
*
* @return Table who owns the pair of values
*/
public String getTable() {
return table;
}
/**
* @param table the table to set
*/
public void setTable(String table) {
this.table = table;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((table == null) ? 0 : table.hashCode());
result = prime * result + ((values == null) ? 0 : values.hashCode());
return result;
}
public Object getProperty(int arg0) {
// TODO Auto-generated method stub
return null;
}
public int getPropertyCount() {
// TODO Auto-generated method stub
return 0;
}
public void getPropertyInfo(int arg0, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo arg2) {
// TODO Auto-generated method stub
}
public void setProperty(int arg0, Object arg1) {
// TODO Auto-generated method stub
}
@Override
public String toString() {
return "PairTable{" +
"values=" + values +
", table='" + table + '\'' +
"} " + super.toString();
}
}

View File

@ -1,12 +1,17 @@
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.io.Serializable; import java.io.Serializable;
import java.util.Hashtable; import java.util.Hashtable;
public class Roles extends Model implements Serializable { import lombok.Data;
@Data
public class Roles implements Serializable, KvmSerializable {
private long id;
private int rol; private int rol;
protected static final PropertyInfo PI_id = new PropertyInfo(); protected static final PropertyInfo PI_id = new PropertyInfo();
@ -21,14 +26,6 @@ public class Roles extends Model implements Serializable {
this.rol = rol; this.rol = rol;
} }
public int getRol() {
return rol;
}
public void setRol(int rol) {
this.rol = rol;
}
@Override @Override
public Object getProperty(int param) { public Object getProperty(int param) {
Object object = null; Object object = null;

View File

@ -18,15 +18,23 @@
*/ */
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.Index;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.util.Hashtable; import java.util.Hashtable;
import lombok.Data;
/** /**
* Class for store a notification * Class for store a notification
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * * @author Juan Miguel Boyero Corral <swadroid@gmail.com> *
*/ */
@Data
@Entity(indices = {@Index("seenLocal"), @Index("seenRemote"), @Index("eventTime")})
public class SWADNotification extends Model { public class SWADNotification extends Model {
/** /**
* Event id (not unique) * Event id (not unique)
@ -84,20 +92,34 @@ public class SWADNotification extends Model {
* Notification has been marked as seen in SWAD * Notification has been marked as seen in SWAD
*/ */
private boolean seenRemote; private boolean seenRemote;
@Ignore
private static final PropertyInfo PI_id = new PropertyInfo(); private static final PropertyInfo PI_id = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_eventCode = new PropertyInfo(); private static final PropertyInfo PI_eventCode = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_eventType = new PropertyInfo(); private static final PropertyInfo PI_eventType = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_eventTime = new PropertyInfo(); private static final PropertyInfo PI_eventTime = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userNickname = new PropertyInfo(); private static final PropertyInfo PI_userNickname = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userSurname1 = new PropertyInfo(); private static final PropertyInfo PI_userSurname1 = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userSurname2 = new PropertyInfo(); private static final PropertyInfo PI_userSurname2 = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userFirstName = new PropertyInfo(); private static final PropertyInfo PI_userFirstName = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userPhoto = new PropertyInfo(); private static final PropertyInfo PI_userPhoto = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_location = new PropertyInfo(); private static final PropertyInfo PI_location = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_summary = new PropertyInfo(); private static final PropertyInfo PI_summary = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_status = new PropertyInfo(); private static final PropertyInfo PI_status = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_content = new PropertyInfo(); private static final PropertyInfo PI_content = new PropertyInfo();
@SuppressWarnings("unused") @Ignore
private static PropertyInfo[] PI_PROP_ARRAY = private static PropertyInfo[] PI_PROP_ARRAY =
{ {
PI_id, PI_id,
@ -115,27 +137,7 @@ public class SWADNotification extends Model {
PI_content PI_content
}; };
/** public SWADNotification(long id, long eventCode, String eventType, long eventTime, String userNickname, String userSurname1, String userSurname2, String userFirstName, String userPhoto, String location, String summary, int status, String content, boolean seenLocal, boolean seenRemote) {
* @param id Notification id (unique)
* @param eventCode Event id (not unique)
* @param eventType Notification type
* @param eventTime Notification timestamp
* @param userNickname Sender nickname
* @param userSurname1 Sender first surname
* @param userSurname2 Sender second surname
* @param userFirstName Sender first name
* @param userPhoto Full URL path of the sender photo
* @param location Notification location
* @param summary Notification summary
* @param status Notification status
* @param seenLocal Notification has been seen locally
* @param seenRemote Notification has been seen in SWAD
*/
public SWADNotification(long id, long eventCode, String eventType, long eventTime,
String userNickname, String userSurname1, String userSurname2,
String userFirstName, String userPhoto, String location, String summary,
int status, String content, boolean seenLocal, boolean seenRemote) {
super(id); super(id);
this.eventCode = eventCode; this.eventCode = eventCode;
this.eventType = eventType; this.eventType = eventType;
@ -153,314 +155,6 @@ public class SWADNotification extends Model {
this.seenRemote = seenRemote; this.seenRemote = seenRemote;
} }
/**
* Gets event id
*
* @return Event id
*/
public long getEventCode() {
return eventCode;
}
/**
* Sets event id
*
* @param eventCode Event id
*/
public void setEventCode(long eventCode) {
this.eventCode = eventCode;
}
/**
* Gets notification type
*
* @return Notification type
*/
public String getEventType() {
return eventType;
}
/**
* Sets notification type
*
* @param eventType Notification type
*/
public void setEventType(String eventType) {
this.eventType = eventType;
}
/**
* Gets notification timestamp
*
* @return Notification timestamp
*/
public long getEventTime() {
return eventTime;
}
/**
* Sets notification timestamp
*
* @param eventTime Notification timestamp
*/
public void setEventTime(int eventTime) {
this.eventTime = eventTime;
}
/**
* Gets sender nickname
*
* @return Sender nickname
*/
public String getUserNickname() {
return userNickname;
}
/**
* Sets sender nickname
*
* @param userNickname Sender nickname
*/
public void setUserNickname(String userNickname) {
this.userNickname = userNickname;
}
/**
* Gets sender first surname
*
* @return Sender first surname
*/
public String getUserSurname1() {
return userSurname1;
}
/**
* Sets sender first surname
*
* @param userSurname1 Sender first surname
*/
public void setUserSurname1(String userSurname1) {
this.userSurname1 = userSurname1;
}
/**
* Gets sender second surname
*
* @return Sender second surname
*/
public String getUserSurname2() {
return userSurname2;
}
/**
* Sets sender second surname
*
* @param userSurname2 Sender second surname
*/
public void setUserSurname2(String userSurname2) {
this.userSurname2 = userSurname2;
}
/**
* Gets sender first name
*
* @return Sender first name
*/
public String getUserFirstName() {
return userFirstName;
}
/**
* Sets sender first name
*
* @param userFirstName Sender first name
*/
public void setUserFirstName(String userFirstName) {
this.userFirstName = userFirstName;
}
/**
* Gets full URL path of the sender photo
*
* @return Full URL path of the sender photo
*/
public String getUserPhoto() {
return userPhoto;
}
/**
* Sets full URL path of the sender photo
*
* @param userPhoto Full URL path of the sender photo
*/
public void setUserPhoto(String userPhoto) {
this.userPhoto = userPhoto;
}
/**
* Gets notification location
*
* @return Notification location
*/
public String getLocation() {
return location;
}
/**
* Sets notification location
*
* @param location Notification location
*/
public void setLocation(String location) {
this.location = location;
}
/**
* Gets notification summary
*
* @return Notification summary
*/
public String getSummary() {
return summary;
}
/**
* Sets notification summary
*
* @param summary Notification summary
*/
public void setSummary(String summary) {
this.summary = summary;
}
/**
* Gets notification status
*
* @return Notification status
*/
public int getStatus() {
return status;
}
/**
* Sets notification status
*
* @param status Notification status
*/
public void setStatus(int status) {
this.status = status;
}
/**
* Gets notification content
*
* @return Notification content
*/
public String getContent() {
return content;
}
/**
* Sets notification content
*
* @param content notification content
*/
public void setContent(String content) {
this.content = content;
}
/**
* Gets notification seenLocal attribute
*
* @return true if notification has been seen locally
* false otherwise
*/
public boolean isSeenLocal() {
return seenLocal;
}
/**
* Sets notification seenLocal attribute
*
* @param seenLocal true if notification has been seen locally
* false otherwise
*/
public void setSeenLocal(boolean seenLocal) {
this.seenLocal = seenLocal;
}
/**
* Gets notification seenRemote attribute
*
* @return true if notification has been seen in SWAD
* false otherwise
*/
public boolean isSeenRemote() {
return seenRemote;
}
/**
* Sets notification seenRemote attribute
*
* @param seenRemote true if notification has been seen in SWAD
* false otherwise
*/
public void setSeenRemote(boolean seenRemote) {
this.seenRemote = seenRemote;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SWADNotification)) return false;
if (!super.equals(o)) return false;
SWADNotification that = (SWADNotification) o;
if (eventCode != that.eventCode) return false;
if (eventTime != that.eventTime) return false;
if (status != that.status) return false;
if (seenLocal != that.seenLocal) return false;
if (seenRemote != that.seenRemote) return false;
if (eventType != null ? !eventType.equals(that.eventType) : that.eventType != null)
return false;
if (userNickname != null ? !userNickname.equals(that.userNickname) : that.userNickname != null)
return false;
if (userSurname1 != null ? !userSurname1.equals(that.userSurname1) : that.userSurname1 != null)
return false;
if (userSurname2 != null ? !userSurname2.equals(that.userSurname2) : that.userSurname2 != null)
return false;
if (userFirstName != null ? !userFirstName.equals(that.userFirstName) : that.userFirstName != null)
return false;
if (userPhoto != null ? !userPhoto.equals(that.userPhoto) : that.userPhoto != null)
return false;
if (location != null ? !location.equals(that.location) : that.location != null)
return false;
if (summary != null ? !summary.equals(that.summary) : that.summary != null) return false;
return content != null ? content.equals(that.content) : that.content == null;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (int) (eventCode ^ (eventCode >>> 32));
result = 31 * result + (eventType != null ? eventType.hashCode() : 0);
result = 31 * result + (int) (eventTime ^ (eventTime >>> 32));
result = 31 * result + (userNickname != null ? userNickname.hashCode() : 0);
result = 31 * result + (userSurname1 != null ? userSurname1.hashCode() : 0);
result = 31 * result + (userSurname2 != null ? userSurname2.hashCode() : 0);
result = 31 * result + (userFirstName != null ? userFirstName.hashCode() : 0);
result = 31 * result + (userPhoto != null ? userPhoto.hashCode() : 0);
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (summary != null ? summary.hashCode() : 0);
result = 31 * result + status;
result = 31 * result + (content != null ? content.hashCode() : 0);
result = 31 * result + (seenLocal ? 1 : 0);
result = 31 * result + (seenRemote ? 1 : 0);
return result;
}
/* (non-Javadoc) /* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#getProperty(int) * @see org.ksoap2.serialization.KvmSerializable#getProperty(int)
*/ */
@ -625,23 +319,4 @@ public class SWADNotification extends Model {
} }
} }
@Override
public String toString() {
return "SWADNotification{" +
"eventCode=" + eventCode +
", eventType='" + eventType + '\'' +
", eventTime=" + eventTime +
", userNickname='" + userNickname + '\'' +
", userSurname1='" + userSurname1 + '\'' +
", userSurname2='" + userSurname2 + '\'' +
", userFirstName='" + userFirstName + '\'' +
", userPhoto='" + userPhoto + '\'' +
", location='" + location + '\'' +
", summary='" + summary + '\'' +
", status=" + status +
", content='" + content + '\'' +
", seenLocal=" + seenLocal +
", seenRemote=" + seenRemote +
"} " + super.toString();
}
} }

View File

@ -18,26 +18,24 @@
*/ */
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import org.ksoap2.serialization.PropertyInfo;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Hashtable;
import java.util.List; import java.util.List;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import es.ugr.swad.swadroid.utils.Utils; import es.ugr.swad.swadroid.utils.Utils;
import lombok.Data;
/** /**
* Class for store a test * Class for store a test
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class Test extends Model { @Data
public class Test {
/** /**
* Correct answer score * Correct answer score
*/ */
private final float CORRECT_ANSWER_SCORE = 1; private static final float CORRECT_ANSWER_SCORE = 1;
/** /**
* None feedback * None feedback
*/ */
@ -62,30 +60,14 @@ public class Test extends Model {
* Feedback values * Feedback values
*/ */
public static final List<String> FEEDBACK_VALUES = Arrays.asList(FEEDBACK_NONE, FEEDBACK_MIN, FEEDBACK_MEDIUM, FEEDBACK_HIGH, FEEDBACK_MAX); public static final List<String> FEEDBACK_VALUES = Arrays.asList(FEEDBACK_NONE, FEEDBACK_MIN, FEEDBACK_MEDIUM, FEEDBACK_HIGH, FEEDBACK_MAX);
/**
* Test config
*/
private final TestConfig testConfig;
/** /**
* List of questions and related answers * List of questions and related answers
*/ */
private List<TestQuestion> questions; private List<TestAnswersQuestion> answersQuestions;
/**
* Minimum questions in test
*/
private int min;
/**
* Default questions in test
*/
private int def;
/**
* Maximum questions in test
*/
private int max;
/**
* Feedback to be showed to the student
*/
private String feedback;
/**
* Last time test was updated
*/
private Long editTime;
/** /**
* Total test's score * Total test's score
*/ */
@ -98,51 +80,10 @@ public class Test extends Model {
* Flag for check if the test has been evaluated * Flag for check if the test has been evaluated
*/ */
private boolean evaluated; private boolean evaluated;
private static final PropertyInfo PI_min = new PropertyInfo();
private static final PropertyInfo PI_def = new PropertyInfo();
private static final PropertyInfo PI_max = new PropertyInfo();
private static final PropertyInfo PI_feedback = new PropertyInfo();
@SuppressWarnings("unused")
private static PropertyInfo[] PI_PROP_ARRAY =
{
PI_min,
PI_def,
PI_max,
PI_feedback
};
/** public Test(TestConfig testConfig, List<TestAnswersQuestion> answersQuestions) {
* Constructor from fields this.testConfig = testConfig;
* this.answersQuestions = answersQuestions;
* @param selectedCourseCode Code of test's course
* @param min Minimum questions in test
* @param def Default questions in test
* @param max Maximum questions in test
* @param feedback Feedback to be showed to the student
*/
public Test(long selectedCourseCode, int min, int def, int max, String feedback) {
super(selectedCourseCode);
this.min = min;
this.def = def;
this.max = max;
this.feedback = feedback;
this.totalScore = 0;
this.questionsScore = new ArrayList<>();
}
/**
* Constructor from fields
*
* @param crsCode Code of test's course
* @param min Minimum questions in test
* @param def Default questions in test
* @param max Maximum questions in test
* @param feedback Feedback to be showed to the student
* @param editTime Last time test was updated
*/
public Test(long crsCode, int min, int def, int max, String feedback, Long editTime) {
this(crsCode, min, def, max, feedback);
this.editTime = editTime;
} }
/** /**
@ -151,116 +92,8 @@ public class Test extends Model {
* @param i Question's position * @param i Question's position
* @return A pair of values <Question, List of answers> * @return A pair of values <Question, List of answers>
*/ */
public TestQuestion getQuestionAndAnswers(int i) { public TestAnswersQuestion getQuestionAndAnswers(int i) {
return questions.get(i); return answersQuestions.get(i);
}
/**
* Gets minimum questions in test
*
* @return Minimum questions in test
*/
public int getMin() {
return min;
}
/**
* Sets minimum questions in test
*
* @param min Minimum questions in test
*/
public void setMin(int min) {
this.min = min;
}
/**
* Gets default questions in test
*
* @return Default questions in test
*/
public int getDef() {
return def;
}
/**
* Sets default questions in test
*
* @param def Default questions in test
*/
public void setDef(int def) {
this.def = def;
}
/**
* Gets maximum questions in test
*
* @return Maximum questions in test
*/
public int getMax() {
return max;
}
/**
* Sets maximum questions in test
*
* @param max Maximum questions in test
*/
public void setMax(int max) {
this.max = max;
}
/**
* Gets feedback to be showed to the student
*
* @return Feedback to be showed to the student
*/
public String getFeedback() {
return feedback;
}
/**
* Sets feedback to be showed to the student
*
* @param feedback Feedback to be showed to the student
*/
public void setFeedback(String feedback) {
this.feedback = feedback;
}
/**
* Gets last time test was updated
*
* @return Last time test was updated
*/
public Long getEditTime() {
return editTime;
}
/**
* Sets last time test was updated
*
* @param timestamp Last time test was updated
*/
public void setEditTime(Long timestamp) {
this.editTime = timestamp;
}
/**
* Gets total test's score
*
* @return Total test's score
*/
public float getTotalScore() {
return totalScore;
}
/**
* Sets total test's score
*
* @param totalScore Total test's score
*/
public void setTotalScore(float totalScore) {
this.totalScore = totalScore;
} }
/** /**
@ -283,62 +116,6 @@ public class Test extends Model {
this.questionsScore.set(pos, score); this.questionsScore.set(pos, score);
} }
/**
* Gets the questions list
*
* @return The questions list
*/
public List<TestQuestion> getQuestions() {
return questions;
}
/**
* Sets the questions list
*
* @param questions The questions to set
*/
public void setQuestions(List<TestQuestion> questions) {
this.questions = questions;
}
/**
* Gets the questions's score
*
* @return The questions's score
*/
public List<Float> getQuestionsScore() {
return questionsScore;
}
/**
* Sets the questions's score
*
* @param questionsScore The questions's score
*/
public void setQuestionsScore(List<Float> questionsScore) {
this.questionsScore = questionsScore;
}
/**
* Checks if the test has been evaluated
*
* @return true if the test has been evaluated
* false if the test hasn't been evaluated
*/
public boolean isEvaluated() {
return evaluated;
}
/**
* Specifies if the test has been evaluated
*
* @param evaluated true if the test has been evaluated
* false if the test hasn't been evaluated
*/
public void setEvaluated(boolean evaluated) {
this.evaluated = evaluated;
}
/** /**
* Initializes questions's score and total score * Initializes questions's score and total score
*/ */
@ -347,7 +124,7 @@ public class Test extends Model {
totalScore = 0; totalScore = 0;
questionsScore.clear(); questionsScore.clear();
for (int i=0; i<this.questions.size(); i++) { for (int i = 0; i<this.answersQuestions.size(); i++) {
this.questionsScore.add((float) 0); this.questionsScore.add((float) 0);
} }
} }
@ -372,12 +149,6 @@ public class Test extends Model {
//Remove accents //Remove accents
s = Utils.unAccent(s); s = Utils.unAccent(s);
/*s = s.replace('á', 'a');
s = s.replace('é', 'e');
s = s.replace('í', 'i');
s = s.replace('ó', 'o');
s = s.replace('ú', 'u');*/
return s; return s;
} }
@ -385,18 +156,29 @@ public class Test extends Model {
* Calculates total score and individual question's score of the test * Calculates total score and individual question's score of the test
*/ */
public void evaluate() { public void evaluate() {
int totalAnswers, trueAnswers, falseAnswers, correctUserAnswers, errors; int totalAnswers;
Float score, userFloatAnswer, minFloatRange, maxFloatRange; int trueAnswers;
int falseAnswers;
int correctUserAnswers;
int errors;
float score;
float userFloatAnswer;
float minFloatRange;
float maxFloatRange;
TestAnswersQuestion aQ;
TestQuestion q; TestQuestion q;
TestAnswer a; TestAnswer a;
List<TestAnswer> la; List<TestAnswer> la;
String answerType, userAnswerText, answerText; String answerType;
String userAnswerText;
String answerText;
boolean noneSelected; boolean noneSelected;
prepareEvaluation(); prepareEvaluation();
for (int i = 0; i < questions.size(); i++) { for (int i = 0; i < answersQuestions.size(); i++) {
q = questions.get(i); aQ = answersQuestions.get(i);
la = q.getAnswers(); q = aQ.testQuestion;
la = aQ.testAnswers;
answerType = q.getAnswerType(); answerType = q.getAnswerType();
totalAnswers = 1; totalAnswers = 1;
trueAnswers = 0; trueAnswers = 0;
@ -410,9 +192,9 @@ public class Test extends Model {
userAnswerText = a.getUserAnswer(); userAnswerText = a.getUserAnswer();
if (!userAnswerText.equals("")) { if (!userAnswerText.equals("")) {
userFloatAnswer = Float.valueOf(userAnswerText); userFloatAnswer = Float.parseFloat(userAnswerText);
minFloatRange = Float.valueOf(a.getAnswer()); minFloatRange = Float.parseFloat(a.getAnswer());
maxFloatRange = Float.valueOf(la.get(1).getAnswer()); maxFloatRange = Float.parseFloat(la.get(1).getAnswer());
a.setCorrectAnswered((userFloatAnswer >= minFloatRange) && (userFloatAnswer <= maxFloatRange)); a.setCorrectAnswered((userFloatAnswer >= minFloatRange) && (userFloatAnswer <= maxFloatRange));
} }
@ -423,7 +205,7 @@ public class Test extends Model {
} }
if (userAnswerText.equals("")) { if (userAnswerText.equals("")) {
score = (float) 0; score = 0;
} else { } else {
score = correctUserAnswers / (float) totalAnswers; score = correctUserAnswers / (float) totalAnswers;
} }
@ -432,7 +214,7 @@ public class Test extends Model {
a = la.get(0); a = la.get(0);
userAnswerText = a.getUserAnswer(); userAnswerText = a.getUserAnswer();
if (a.getCorrect()) { if (a.isCorrect()) {
a.setCorrectAnswered(a.getAnswer().equals(a.getUserAnswer())); a.setCorrectAnswered(a.getAnswer().equals(a.getUserAnswer()));
} else { } else {
a.setCorrectAnswered(!a.getAnswer().equals(a.getUserAnswer())); a.setCorrectAnswered(!a.getAnswer().equals(a.getUserAnswer()));
@ -445,9 +227,9 @@ public class Test extends Model {
} }
if (userAnswerText.equals("")) { if (userAnswerText.equals("")) {
score = (float) 0; score = 0;
} else { } else {
score = (float) (correctUserAnswers - errors); score = (correctUserAnswers - errors);
} }
break; break;
case "int": case "int":
@ -462,7 +244,7 @@ public class Test extends Model {
} }
if (userAnswerText.equals("")) { if (userAnswerText.equals("")) {
score = (float) 0; score = 0;
} else { } else {
score = correctUserAnswers / (float) totalAnswers; score = correctUserAnswers / (float) totalAnswers;
} }
@ -488,7 +270,7 @@ public class Test extends Model {
} }
if (userAnswerText.equals("")) { if (userAnswerText.equals("")) {
score = (float) 0; score = 0;
} else { } else {
score = correctUserAnswers / (float) totalAnswers; score = correctUserAnswers / (float) totalAnswers;
} }
@ -499,7 +281,7 @@ public class Test extends Model {
a.setCorrectAnswered(false); a.setCorrectAnswered(false);
for (TestAnswer ans : la) { for (TestAnswer ans : la) {
if (ans.getCorrect() && ans.getAnswer().equals(a.getUserAnswer())) { if (ans.isCorrect() && ans.getAnswer().equals(a.getUserAnswer())) {
a.setCorrectAnswered(true); a.setCorrectAnswered(true);
break; break;
} }
@ -512,7 +294,7 @@ public class Test extends Model {
} }
if (a.getUserAnswer().equals("")) { if (a.getUserAnswer().equals("")) {
score = (float) 0; score = 0;
} else { } else {
score = correctUserAnswers - (errors / ((float) totalAnswers - 1)); score = correctUserAnswers - (errors / ((float) totalAnswers - 1));
} }
@ -521,14 +303,12 @@ public class Test extends Model {
noneSelected = true; noneSelected = true;
totalAnswers = la.size(); totalAnswers = la.size();
for (TestAnswer ans : la) { for (TestAnswer ans : la) {
if (ans.getCorrect()) { if (ans.isCorrect()) {
trueAnswers++; trueAnswers++;
if (ans.getUserAnswer().equals("Y")) { if (ans.getUserAnswer().equals("Y")) {
correctUserAnswers++; correctUserAnswers++;
noneSelected = false; noneSelected = false;
}/* else { }
errors++;
}*/
} else { } else {
falseAnswers++; falseAnswers++;
if (ans.getUserAnswer().equals("Y")) { if (ans.getUserAnswer().equals("Y")) {
@ -539,7 +319,7 @@ public class Test extends Model {
} }
if (noneSelected) { if (noneSelected) {
score = (float) 0; score = 0;
} else { } else {
if (falseAnswers == 0) { if (falseAnswers == 0) {
score = correctUserAnswers / (float) totalAnswers; score = correctUserAnswers / (float) totalAnswers;
@ -557,93 +337,4 @@ public class Test extends Model {
evaluated = true; evaluated = true;
} }
/* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#getProperty(int)
*/
public Object getProperty(int param) {
Object object = null;
switch (param) {
case 1:
object = min;
break;
case 2:
object = def;
break;
case 3:
object = max;
break;
case 4:
object = feedback;
break;
}
return object;
}
/* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#getPropertyCount()
*/
public int getPropertyCount() {
return PI_PROP_ARRAY.length;
}
/* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#getPropertyInfo(int, java.util.Hashtable, org.ksoap2.serialization.PropertyInfo)
*/
public void getPropertyInfo(int param, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo propertyInfo) {
switch (param) {
case 0:
propertyInfo.type = PropertyInfo.INTEGER_CLASS;
propertyInfo.name = "min";
break;
case 1:
propertyInfo.type = PropertyInfo.INTEGER_CLASS;
propertyInfo.name = "def";
break;
case 2:
propertyInfo.type = PropertyInfo.INTEGER_CLASS;
propertyInfo.name = "max";
break;
case 3:
propertyInfo.type = PropertyInfo.STRING_CLASS;
propertyInfo.name = "feedback";
break;
}
}
/* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#setProperty(int, java.lang.Object)
*/
public void setProperty(int param, Object obj) {
switch (param) {
case 0:
min = (Integer) obj;
break;
case 1:
def = (Integer) obj;
break;
case 2:
max = (Integer) obj;
break;
case 3:
feedback = (String) obj;
break;
}
}
@Override
public String toString() {
return "Test{" +
"CORRECT_ANSWER_SCORE=" + CORRECT_ANSWER_SCORE +
", questions=" + questions +
", min=" + min +
", def=" + def +
", max=" + max +
", feedback='" + feedback + '\'' +
", editTime=" + editTime +
", totalScore=" + totalScore +
", questionsScore=" + questionsScore +
", evaluated=" + evaluated +
"} " + super.toString();
}
} }

View File

@ -18,20 +18,34 @@
*/ */
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.Ignore;
import androidx.room.Index;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.util.Hashtable; import java.util.Hashtable;
import lombok.Data;
/** /**
* Class for store a test answer * Class for store a test answer
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
@Data
@Entity(indices = {@Index("qstCod"), @Index("ansInd")},
foreignKeys = {
@ForeignKey(entity = TestQuestion.class,
parentColumns = "id",
childColumns = "qstCod",
onDelete = ForeignKey.CASCADE)})
public class TestAnswer extends Model { public class TestAnswer extends Model {
/** /**
* Question code; * Question code;
*/ */
private int qstCod; private long qstCod;
/** /**
* Answer index; * Answer index;
*/ */
@ -43,6 +57,7 @@ public class TestAnswer extends Model {
/** /**
* Flag to know if the user has answered correctly * Flag to know if the user has answered correctly
*/ */
@Ignore
private boolean correctAnswered; private boolean correctAnswered;
/** /**
* Answer's text * Answer's text
@ -52,6 +67,11 @@ public class TestAnswer extends Model {
* Answer's feedback * Answer's feedback
*/ */
private String feedback; private String feedback;
/**
* User answer
*/
@Ignore
private String userAnswer;
/** /**
* Type integer * Type integer
*/ */
@ -84,17 +104,20 @@ public class TestAnswer extends Model {
* False value * False value
*/ */
public static final String VALUE_FALSE = "F"; public static final String VALUE_FALSE = "F";
/**
* User answer @Ignore
*/
private String userAnswer;
private static final PropertyInfo PI_id = new PropertyInfo(); private static final PropertyInfo PI_id = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_correct = new PropertyInfo(); private static final PropertyInfo PI_correct = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_correctAnswered = new PropertyInfo(); private static final PropertyInfo PI_correctAnswered = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_answer = new PropertyInfo(); private static final PropertyInfo PI_answer = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_ansInd = new PropertyInfo(); private static final PropertyInfo PI_ansInd = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_feedback = new PropertyInfo(); private static final PropertyInfo PI_feedback = new PropertyInfo();
@SuppressWarnings("unused") @Ignore
private static PropertyInfo[] PI_PROP_ARRAY = private static PropertyInfo[] PI_PROP_ARRAY =
{ {
PI_id, PI_id,
@ -105,178 +128,19 @@ public class TestAnswer extends Model {
PI_feedback PI_feedback
}; };
/** public TestAnswer(long id, long qstCod, int ansInd, boolean correct, String answer, String feedback) {
* Constructor
*
* @param id Answer id
* @param ansInd Answer index inside the question
* @param qstCod Question code
* @param correct Flag to know if this is the correct answer of the question
* @param answer Answer's text
* @param feedback Text of the answer's feedback
*/
public TestAnswer(long id, int ansInd, int qstCod, boolean correct, String answer, String feedback) {
super(id); super(id);
this.ansInd = ansInd;
this.qstCod = qstCod; this.qstCod = qstCod;
this.ansInd = ansInd;
this.correct = correct; this.correct = correct;
this.correctAnswered = false;
this.answer = answer; this.answer = answer;
this.userAnswer = "";
this.feedback = feedback; this.feedback = feedback;
} }
/** public TestAnswer(long id, int qstCod, int ansInd, boolean correct, boolean correctAnswered, String answer, String feedback, String userAnswer) {
* Gets answer correct flag this(id, qstCod, ansInd, correct, answer, feedback);
*
* @return Answer correct flag
*/
public boolean getCorrect() {
return correct;
}
/**
* Sets answer correct flag
*/
public void setCorrect(boolean correct) {
this.correct = correct;
}
/**
* Gets answer text
*
* @return Answer text
*/
public String getAnswer() {
return answer;
}
/**
* Sets answer text
*
* @param answer Answer text
*/
public void setAnswer(String answer) {
this.answer = answer;
}
/**
* Gets question code
*
* @return Question code
*/
public int getQstCod() {
return qstCod;
}
/**
* Sets question code
*
* @param qstCod question code
*/
public void setQstCod(int qstCod) {
this.qstCod = qstCod;
}
/**
* Gets the user answer
*
* @return User answer
*/
public String getUserAnswer() {
return userAnswer;
}
/**
* Sets user answer text
*
* @param userAnswer User answer text
*/
public void setUserAnswer(String userAnswer) {
this.userAnswer = userAnswer;
}
/**
* Checks if the user has answered correctly
*
* @return true if the user has answered correctly
* false otherwise
*/
public boolean isCorrectAnswered() {
return correctAnswered;
}
/**
* Marks this answer as correctly or incorrectly answered by the user
*
* @param correctAnswered true if the user has answered correctly
* false otherwise
*/
public void setCorrectAnswered(boolean correctAnswered) {
this.correctAnswered = correctAnswered; this.correctAnswered = correctAnswered;
} this.userAnswer = userAnswer;
/**
* Gets the answer index inside the question
*
* @return Answer index inside the question
*/
public int getAnsInd() {
return ansInd;
}
/**
* Sets the answer index inside the question
*
* @param ansInd Answer index inside the question
*/
public void setAnsInd(int ansInd) {
this.ansInd = ansInd;
}
/**
* Gets the text of the answer's feedback
*
* @return Text of the answer's feedback
*/
public String getFeedback() {
return feedback;
}
/**
* Sets the text of the answer's feedback
*
* @param feedback Text of the answer's feedback
*/
public void setFeedback(String feedback) {
this.feedback = feedback;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ansInd;
result = prime * result + ((answer == null) ? 0 : answer.hashCode());
result = prime * result + (correct ? 1231 : 1237);
result = prime * result + (correctAnswered ? 1231 : 1237);
result = prime * result
+ ((feedback == null) ? 0 : feedback.hashCode());
result = prime * result + qstCod;
result = prime * result
+ ((userAnswer == null) ? 0 : userAnswer.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
return this == obj || super.equals(obj) && getClass() == obj.getClass();
} }
/* (non-Javadoc) /* (non-Javadoc)
@ -318,7 +182,7 @@ public class TestAnswer extends Model {
/* (non-Javadoc) /* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#getPropertyInfo(int, java.util.Hashtable, org.ksoap2.serialization.PropertyInfo) * @see org.ksoap2.serialization.KvmSerializable#getPropertyInfo(int, java.util.Hashtable, org.ksoap2.serialization.PropertyInfo)
*/ */
public void getPropertyInfo(int param, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo propertyInfo) { public void getPropertyInfo(int param, Hashtable arg1, PropertyInfo propertyInfo) {
switch (param) { switch (param) {
case 0: case 0:
propertyInfo.type = PropertyInfo.LONG_CLASS; propertyInfo.type = PropertyInfo.LONG_CLASS;
@ -373,16 +237,4 @@ public class TestAnswer extends Model {
} }
} }
@Override
public String toString() {
return "TestAnswer{" +
"qstCod=" + qstCod +
", ansInd=" + ansInd +
", correct=" + correct +
", correctAnswered=" + correctAnswered +
", answer='" + answer + '\'' +
", feedback='" + feedback + '\'' +
", userAnswer='" + userAnswer + '\'' +
"} " + super.toString();
}
} }

View File

@ -0,0 +1,42 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.model;
import androidx.room.Embedded;
import androidx.room.Relation;
import java.util.List;
import lombok.Data;
/**
* Test answers related to a question.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>.
*/
@Data
public class TestAnswersQuestion {
@Embedded
public TestQuestion testQuestion;
@Relation(
parentColumn = "id",
entityColumn = "qstCod"
)
public List<TestAnswer> testAnswers;
}

View File

@ -0,0 +1,159 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.model;
import androidx.room.Entity;
import androidx.room.Ignore;
import org.ksoap2.serialization.PropertyInfo;
import java.util.Hashtable;
import lombok.Data;
/**
* Class for store a test config
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/
@Data
@Entity
public class TestConfig extends Model {
/**
* Minimum questions in test
*/
private int min;
/**
* Default questions in test
*/
private int def;
/**
* Maximum questions in test
*/
private int max;
/**
* Feedback to be showed to the student
*/
private String feedback;
/**
* Last time test was updated
*/
private Long editTime;
@Ignore
private static final PropertyInfo PI_min = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_def = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_max = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_feedback = new PropertyInfo();
@Ignore
private static PropertyInfo[] PI_PROP_ARRAY =
{
PI_min,
PI_def,
PI_max,
PI_feedback
};
public TestConfig(long id, int min, int def, int max, String feedback, Long editTime) {
super(id);
this.min = min;
this.def = def;
this.max = max;
this.feedback = feedback;
this.editTime = editTime;
}
/* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#getProperty(int)
*/
public Object getProperty(int param) {
Object object = null;
switch (param) {
case 1:
object = min;
break;
case 2:
object = def;
break;
case 3:
object = max;
break;
case 4:
object = feedback;
break;
}
return object;
}
/* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#getPropertyCount()
*/
public int getPropertyCount() {
return PI_PROP_ARRAY.length;
}
/* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#getPropertyInfo(int, java.util.Hashtable, org.ksoap2.serialization.PropertyInfo)
*/
public void getPropertyInfo(int param, Hashtable arg1, PropertyInfo propertyInfo) {
switch (param) {
case 0:
propertyInfo.type = PropertyInfo.INTEGER_CLASS;
propertyInfo.name = "min";
break;
case 1:
propertyInfo.type = PropertyInfo.INTEGER_CLASS;
propertyInfo.name = "def";
break;
case 2:
propertyInfo.type = PropertyInfo.INTEGER_CLASS;
propertyInfo.name = "max";
break;
case 3:
propertyInfo.type = PropertyInfo.STRING_CLASS;
propertyInfo.name = "feedback";
break;
}
}
/* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#setProperty(int, java.lang.Object)
*/
public void setProperty(int param, Object obj) {
switch (param) {
case 0:
min = (Integer) obj;
break;
case 1:
def = (Integer) obj;
break;
case 2:
max = (Integer) obj;
break;
case 3:
feedback = (String) obj;
break;
}
}
}

View File

@ -18,20 +18,30 @@
*/ */
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.Ignore;
import androidx.room.Index;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.List;
import es.ugr.swad.swadroid.utils.Utils; import es.ugr.swad.swadroid.utils.Utils;
import lombok.Data;
/** /**
* Clas for store a test question * Class for store a test question
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
@Data
@Entity(indices = {@Index("crsCod"), @Index("answerType"), @Index("shuffle")},
foreignKeys = {
@ForeignKey(entity = Course.class,
parentColumns = "id",
childColumns = "crsCod",
onDelete = ForeignKey.CASCADE)})
public class TestQuestion extends Model { public class TestQuestion extends Model {
/** /**
* Course code * Course code
@ -54,17 +64,19 @@ public class TestQuestion extends Model {
*/ */
private String feedback; private String feedback;
/** @Ignore
* Question's answers
*/
private List<TestAnswer> answers;
private static final PropertyInfo PI_id = new PropertyInfo(); private static final PropertyInfo PI_id = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_stem = new PropertyInfo(); private static final PropertyInfo PI_stem = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_editTime = new PropertyInfo(); private static final PropertyInfo PI_editTime = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_ansType = new PropertyInfo(); private static final PropertyInfo PI_ansType = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_shuffle = new PropertyInfo(); private static final PropertyInfo PI_shuffle = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_feedback = new PropertyInfo(); private static final PropertyInfo PI_feedback = new PropertyInfo();
@SuppressWarnings("unused") @Ignore
private static PropertyInfo[] PI_PROP_ARRAY = private static PropertyInfo[] PI_PROP_ARRAY =
{ {
PI_id, PI_id,
@ -75,204 +87,15 @@ public class TestQuestion extends Model {
PI_feedback PI_feedback
}; };
/** public TestQuestion(long id, long crsCod, String stem, String answerType, boolean shuffle, String feedback) {
* @param id Test identifier
* @param stem Question's text
* @param anstype Answer type
* @param shuffle Flag to shuffle answers in test
* @param feedback Text of the question's feedback
*/
public TestQuestion(long id, String stem, String anstype, boolean shuffle, String feedback) {
super(id); super(id);
this.stem = stem;
this.answerType = anstype;
this.shuffle = shuffle;
this.answers = new ArrayList<>();
this.feedback = feedback;
}
/**
* @param id Test identifier
* @param selectedCourseCode Course code
* @param stem Question's text
* @param anstype Answer type
* @param shuffle Flag to shuffle answers in test
* @param feedback Text of the question's feedback
*/
public TestQuestion(long id, long selectedCourseCode, String stem, String anstype, boolean shuffle, String feedback) {
super(id);
this.crsCod = selectedCourseCode;
this.stem = stem;
this.answerType = anstype;
this.shuffle = shuffle;
this.answers = new ArrayList<>();
this.feedback = feedback;
}
/**
* Gets question code
*
* @return Question code
*/
public long getCrsCod() {
return crsCod;
}
/**
* Sets question code
*
* @param crsCod Question code
*/
public void setCrsCod(long crsCod) {
this.crsCod = crsCod; this.crsCod = crsCod;
}
/**
* Gets question's text
*
* @return Question's text
*/
public String getStem() {
return stem;
}
/**
* Sets question's text
*
* @param stem Question's text
*/
public void setStem(String stem) {
this.stem = stem; this.stem = stem;
} this.answerType = answerType;
/**
* Gets answer type
*
* @return Answer type
*/
public String getAnswerType() {
return answerType;
}
/**
* Sets answer type
*
* @param anstype Answer type
*/
public void setAnswerType(String anstype) {
this.answerType = anstype;
}
/**
* Gets shuffle flag
*
* @return Shuffle flag
*/
public boolean getShuffle() {
return shuffle;
}
/**
* Sets shuffle flag
*
* @param shuffle Shuffle flag
*/
public void setShuffle(boolean shuffle) {
this.shuffle = shuffle; this.shuffle = shuffle;
}
/**
* Gets question's answers
*
* @return Question's answers
*/
public List<TestAnswer> getAnswers() {
return answers;
}
/**
* Sets question's answers
*
* @param answers Question's answers
*/
public void setAnswers(List<TestAnswer> answers) {
this.answers = answers;
}
/**
* Gets the text of the question's feedback
*
* @return Text of the question's feedback
*/
public String getFeedback() {
return feedback;
}
/**
* Sets the text of the question's feedback
*
* @param feedback Text of the question's feedback
*/
public void setFeedback(String feedback) {
this.feedback = feedback; this.feedback = feedback;
} }
/**
* Gets correct answer for this test
*
* @return Correct test's answer
*/
public List<TestAnswer> getCorrectAnswers() {
List<TestAnswer> corrects = new ArrayList<>();
TestAnswer current;
for (TestAnswer answer : this.answers) {
current = answer;
if (current.getCorrect()) {
corrects.add(current);
}
}
if (corrects.isEmpty()) {
corrects = null;
}
return corrects;
}
/**
* Shuffles the list of related answers in a question
*/
public void shuffleAnswers() {
Collections.shuffle(answers);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result
+ ((answerType == null) ? 0 : answerType.hashCode());
result = prime * result + ((answers == null) ? 0 : answers.hashCode());
result = prime * result + (int) (crsCod ^ (crsCod >>> 32));
result = prime * result
+ ((feedback == null) ? 0 : feedback.hashCode());
result = prime * result + (shuffle ? 1231 : 1237);
result = prime * result + ((stem == null) ? 0 : stem.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
return this == obj || super.equals(obj) && getClass() == obj.getClass();
}
/* (non-Javadoc) /* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#getProperty(int) * @see org.ksoap2.serialization.KvmSerializable#getProperty(int)
*/ */
@ -309,7 +132,7 @@ public class TestQuestion extends Model {
/* (non-Javadoc) /* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#getPropertyInfo(int, java.util.Hashtable, org.ksoap2.serialization.PropertyInfo) * @see org.ksoap2.serialization.KvmSerializable#getPropertyInfo(int, java.util.Hashtable, org.ksoap2.serialization.PropertyInfo)
*/ */
public void getPropertyInfo(int param, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo propertyInfo) { public void getPropertyInfo(int param, Hashtable arg1, PropertyInfo propertyInfo) {
switch (param) { switch (param) {
case 0: case 0:
propertyInfo.type = PropertyInfo.LONG_CLASS; propertyInfo.type = PropertyInfo.LONG_CLASS;
@ -357,15 +180,4 @@ public class TestQuestion extends Model {
} }
} }
@Override
public String toString() {
return "TestQuestion{" +
"crsCod=" + crsCod +
", stem='" + stem + '\'' +
", answerType='" + answerType + '\'' +
", shuffle=" + shuffle +
", feedback='" + feedback + '\'' +
", answers=" + answers +
"} " + super.toString();
}
} }

View File

@ -0,0 +1,42 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.model;
import androidx.room.Embedded;
import androidx.room.Relation;
import java.util.List;
import lombok.Data;
/**
* Test questions related to a course.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>.
*/
@Data
public class TestQuestionsCourse {
@Embedded
public Course course;
@Relation(
parentColumn = "id",
entityColumn = "crsCod"
)
public List<TestQuestion> testQuestions;
}

View File

@ -18,102 +18,43 @@
*/ */
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.Index;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.util.ArrayList;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.List;
import lombok.Data;
/** /**
* Class for store a test tag * Class for store a test tag
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
@Data
@Entity(indices = {@Index("tagTxt")})
public class TestTag extends Model { public class TestTag extends Model {
/**
* Question codes;
*/
private List<Integer> qstCodList;
/** /**
* Tag text * Tag text
*/ */
private String tagTxt; private String tagTxt;
/**
* Tag index @Ignore
*/
private int tagInd;
private static final PropertyInfo PI_id = new PropertyInfo(); private static final PropertyInfo PI_id = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_tagText = new PropertyInfo(); private static final PropertyInfo PI_tagText = new PropertyInfo();
private static final PropertyInfo PI_tagInd = new PropertyInfo(); @Ignore
@SuppressWarnings("unused")
private static PropertyInfo[] PI_PROP_ARRAY = private static PropertyInfo[] PI_PROP_ARRAY =
{ {
PI_id, PI_id,
PI_tagText, PI_tagText
PI_tagInd
}; };
/** public TestTag(long id, String tagTxt) {
* Constructor
*
* @param id tag id
* @param tagTxt Tag text
* @param tagInd Tag index
*/
public TestTag(long id, String tagTxt, int tagInd) {
super(id); super(id);
this.tagTxt = tagTxt; this.tagTxt = tagTxt;
this.tagInd = tagInd;
}
/**
* Constructor
*
* @param id tag id
* @param tagTxt Tag text
* @param tagInd Tag index
*/
public TestTag(long id, List<Integer> qstCodList, String tagTxt, int tagInd) {
super(id);
this.qstCodList = qstCodList;
this.tagTxt = tagTxt;
this.tagInd = tagInd;
}
/**
* Gets tag text
*
* @return Tag text
*/
public String getTagTxt() {
return tagTxt;
}
/**
* Sets tag text
*
* @param tagTxt Tag text
*/
public void setTagTxt(String tagTxt) {
this.tagTxt = tagTxt;
}
/**
* Gets tag index
*
* @return Tag index
*/
public int getTagInd() {
return tagInd;
}
/**
* Sets tag index
*
* @param tagInd Tag index
*/
public void setTagInd(int tagInd) {
this.tagInd = tagInd;
} }
/* (non-Javadoc) /* (non-Javadoc)
@ -128,9 +69,6 @@ public class TestTag extends Model {
case 1: case 1:
object = tagTxt; object = tagTxt;
break; break;
case 2:
object = tagInd;
break;
} }
return object; return object;
@ -146,7 +84,7 @@ public class TestTag extends Model {
/* (non-Javadoc) /* (non-Javadoc)
* @see org.ksoap2.serialization.KvmSerializable#getPropertyInfo(int, java.util.Hashtable, org.ksoap2.serialization.PropertyInfo) * @see org.ksoap2.serialization.KvmSerializable#getPropertyInfo(int, java.util.Hashtable, org.ksoap2.serialization.PropertyInfo)
*/ */
public void getPropertyInfo(int param, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo propertyInfo) { public void getPropertyInfo(int param, Hashtable arg1, PropertyInfo propertyInfo) {
switch (param) { switch (param) {
case 0: case 0:
propertyInfo.type = PropertyInfo.LONG_CLASS; propertyInfo.type = PropertyInfo.LONG_CLASS;
@ -156,10 +94,6 @@ public class TestTag extends Model {
propertyInfo.type = PropertyInfo.STRING_CLASS; propertyInfo.type = PropertyInfo.STRING_CLASS;
propertyInfo.name = "tagTxt"; propertyInfo.name = "tagTxt";
break; break;
case 2:
propertyInfo.type = PropertyInfo.INTEGER_CLASS;
propertyInfo.name = "tagInd";
break;
} }
} }
@ -174,59 +108,7 @@ public class TestTag extends Model {
case 1: case 1:
tagTxt = (String) obj; tagTxt = (String) obj;
break; break;
case 2:
tagInd = (Integer) obj;
break;
} }
} }
/**
* Gets question codes
*
* @return Question codes
*/
public List<Integer> getQstCodList() {
return qstCodList;
}
/**
* Sets question codes
*
* @param qstCodList Question codes
*/
public void setQstCodList(List<Integer> qstCodList) {
this.qstCodList = qstCodList;
}
/**
* Gets the question code in position i
*
* @param i Position of question code
* @return Question code
*/
public Integer getQstCod(int i) {
return this.qstCodList.get(i);
}
/**
* Adds a question code to the list
*
* @param qstCod Question code to be added
*/
public void addQstCod(Integer qstCod) {
if (this.qstCodList == null) {
this.qstCodList = new ArrayList<>();
}
this.qstCodList.add(qstCod);
}
@Override
public String toString() {
return "TestTag{" +
"qstCodList=" + qstCodList +
", tagTxt='" + tagTxt + '\'' +
", tagInd=" + tagInd +
"} " + super.toString();
}
} }

View File

@ -0,0 +1,55 @@
/*
* This file is part of SWADroid.
*
* Copyright (C) 2010 Juan Miguel Boyero Corral <juanmi1982@gmail.com>
*
* SWADroid is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SWADroid is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SWADroid. If not, see <http://www.gnu.org/licenses/>.
*/
package es.ugr.swad.swadroid.model;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.Index;
import lombok.Data;
/**
* Relation between Test tags and questions.
*
* @author Juan Miguel Boyero Corral <swadroid@gmail.com>.
*/
@Data
@Entity(indices = {@Index("tagCod"), @Index("qstCod")},
primaryKeys = {"tagCod", "qstCod"},
foreignKeys = {
@ForeignKey(entity = TestQuestion.class,
parentColumns = "id",
childColumns = "qstCod",
onDelete = ForeignKey.CASCADE),
@ForeignKey(entity = TestTag.class,
parentColumns = "id",
childColumns = "tagCod",
onDelete = ForeignKey.CASCADE)
})
public class TestTagsQuestions {
private long qstCod;
private long tagCod;
private int tagIndex;
public TestTagsQuestions(long qstCod, long tagCod, int tagIndex) {
this.qstCod = qstCod;
this.tagCod = tagCod;
this.tagIndex = tagIndex;
}
}

View File

@ -19,23 +19,28 @@
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.Index;
import androidx.room.TypeConverters;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar; import java.util.Calendar;
import java.util.Hashtable; import java.util.Hashtable;
import java.util.Locale;
import es.ugr.swad.swadroid.Constants; import es.ugr.swad.swadroid.converters.CalendarConverter;
import lombok.Data;
/** /**
* User data. * User data.
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
* @author Antonio Aguilera Malagon <aguilerin@gmail.com> * @author Antonio Aguilera Malagon <aguilerin@gmail.com>
*/ */
@Data
@TypeConverters({CalendarConverter.class})
@Entity(indices = {@Index("userNickname")})
public class User extends Model { public class User extends Model {
/** /**
* Webservices session key. * Webservices session key.
@ -74,17 +79,25 @@ public class User extends Model {
*/ */
private int userRole; private int userRole;
@Ignore
private static final PropertyInfo PI_wsKey = new PropertyInfo(); private static final PropertyInfo PI_wsKey = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userID = new PropertyInfo(); private static final PropertyInfo PI_userID = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userNickname = new PropertyInfo(); private static final PropertyInfo PI_userNickname = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userSurname1 = new PropertyInfo(); private static final PropertyInfo PI_userSurname1 = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userSurname2 = new PropertyInfo(); private static final PropertyInfo PI_userSurname2 = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userFirstname = new PropertyInfo(); private static final PropertyInfo PI_userFirstname = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userPhoto = new PropertyInfo(); private static final PropertyInfo PI_userPhoto = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userBirthday = new PropertyInfo(); private static final PropertyInfo PI_userBirthday = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userRole = new PropertyInfo(); private static final PropertyInfo PI_userRole = new PropertyInfo();
@Ignore
@SuppressWarnings("unused")
private static PropertyInfo[] PI_PROP_ARRAY = { private static PropertyInfo[] PI_PROP_ARRAY = {
PI_wsKey, PI_wsKey,
PI_userID, PI_userID,
@ -97,8 +110,7 @@ public class User extends Model {
PI_userRole PI_userRole
}; };
private static DateFormat dateFormat = DateFormat.getDateInstance(); @Ignore
public User() { public User() {
super(-1); super(-1);
} }
@ -119,7 +131,7 @@ public class User extends Model {
*/ */
public User(long id, String wsKey, String userID, String userNickname, String userSurname1, public User(long id, String wsKey, String userID, String userNickname, String userSurname1,
String userSurname2, String userFirstname, String userPhoto, String userBirthday, String userSurname2, String userFirstname, String userPhoto, String userBirthday,
int userRole) throws ParseException { int userRole) {
super(id); super(id);
this.wsKey = wsKey; this.wsKey = wsKey;
this.userID = userID; this.userID = userID;
@ -132,124 +144,23 @@ public class User extends Model {
this.userRole = userRole; this.userRole = userRole;
} }
/** public User(long id, String wsKey, String userID, String userNickname, String userSurname1,
* Gets user name. String userSurname2, String userFirstname, String userPhoto, Calendar userBirthday,
* int userRole) {
* @return User name. super(id);
*/ this.wsKey = wsKey;
public String getUserFirstname() {
return userFirstname;
}
/**
* Sets user name.
*
* @param userFirstname User name.
*/
public void setUserFirstname(String userFirstname) {
this.userFirstname = userFirstname;
}
/**
* Gets user identifier.
*
* @return User identifier.
*/
public String getUserID() {
return userID;
}
/**
* Sets user identifier.
*
* @param userID User identifier.
*/
public void setUserID(String userID) {
this.userID = userID; this.userID = userID;
} this.userNickname = userNickname;
/**
* Gets user nickname.
*
* @return User nickname.
*/
public String getUserNickname() {
return userNickname;
}
/**
* Sets user nickname.
*
* @param userNickname User nickname.
*/
public void setUserNickname(String userNickname) {
this.userID = userNickname;
}
/**
* Gets user first surname.
*
* @return User first surname.
*/
public String getUserSurname1() {
return userSurname1;
}
/**
* Sets user first surname.
*
* @param userSurname1 User first surname.
*/
public void setUserSurname1(String userSurname1) {
this.userSurname1 = userSurname1; this.userSurname1 = userSurname1;
}
/**
* Gets user last surname.
*
* @return User last surname.
*/
public String getUserSurname2() {
return userSurname2;
}
/**
* Sets user last surname.
*
* @param userSurname2 User last surname.
*/
public void setUserSurname2(String userSurname2) {
this.userSurname2 = userSurname2; this.userSurname2 = userSurname2;
this.userFirstname = userFirstname;
this.userPhoto = userPhoto;
this.userBirthday = userBirthday;
this.userRole = userRole;
} }
/** public void setUserBirthday(Calendar userBirthday) {
* Gets Full path where user's picture is stored. this.userBirthday = userBirthday;
*
* @return the userPhoto
*/
public String getUserPhoto() {
return userPhoto;
}
/**
* Gets File name where user's picture is stored.
*
* @return the userPhoto
*/
public String getPhotoFileName() {
if (userPhoto == null || userPhoto.equals(""))
return null;
else
return userPhoto.substring(userPhoto.lastIndexOf('/') + 1);
}
/**
* Gets user birthday.
*
* @return User birthday.
*/
public Calendar getUserBirthday() {
return userBirthday;
} }
/** /**
@ -257,60 +168,8 @@ public class User extends Model {
* *
* @param userBirthday User birthday. * @param userBirthday User birthday.
*/ */
private void setUserBirthday(String userBirthday) throws ParseException { public void setUserBirthday(String userBirthday) {
if((userBirthday != null) && !userBirthday.equals(Constants.NULL_VALUE) && !userBirthday.equals("00000000")) { this.userBirthday = CalendarConverter.toCalendar(userBirthday);
this.userBirthday = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
this.userBirthday.setTime(sdf.parse(userBirthday));
} else {
this.userBirthday = null;
}
}
/**
* Sets Full path where user's picture is stored.
*
* @param userPhoto the userPhoto to set
*/
public void setUserPhoto(String userPhoto) {
this.userPhoto = userPhoto;
}
/**
* Gets User role.
*
* @return User role.
*/
public int getUserRole() {
return userRole;
}
/**
* Sets User role.
*
* @param userRole User role.
*/
public void setUserRole(int userRole) {
this.userRole = userRole;
}
/**
* Gets Webservices session key.
*
* @return Webservices session key.
*/
public String getWsKey() {
return wsKey;
}
/**
* Sets Webservices session key.
*
* @param wsKey Webservices session key.
*/
public void setWsKey(String wsKey) {
this.wsKey = wsKey;
} }
public Object getProperty(int param) { public Object getProperty(int param) {
@ -425,18 +284,4 @@ public class User extends Model {
} }
} }
@Override
public String toString() {
return "User{" +
"wsKey='" + wsKey + '\'' +
", userID='" + userID + '\'' +
", userNickname='" + userNickname + '\'' +
", userSurname1='" + userSurname1 + '\'' +
", userSurname2='" + userSurname2 + '\'' +
", userFirstname='" + userFirstname + '\'' +
", userPhoto='" + userPhoto + '\'' +
", userBirthday=" + userBirthday +
", userRole=" + userRole +
"} " + super.toString();
}
} }

View File

@ -21,18 +21,38 @@
package es.ugr.swad.swadroid.model; package es.ugr.swad.swadroid.model;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.Ignore;
import androidx.room.Index;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.util.Hashtable; import java.util.Hashtable;
import lombok.Data;
/** /**
* User attendance data. * User attendance data.
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
@Data
@Entity(indices = {@Index("eventCode")},
foreignKeys = {
@ForeignKey(entity = User.class,
parentColumns = "id",
childColumns = "id",
onDelete = ForeignKey.CASCADE),
@ForeignKey(entity = Event.class,
parentColumns = "id",
childColumns = "eventCode",
onDelete = ForeignKey.CASCADE)
}
)
public class UserAttendance extends Model { public class UserAttendance extends Model {
/** /**
* User identifier. * Event identifier.
*/ */
private int eventCode; private int eventCode;
/** /**
@ -40,15 +60,21 @@ public class UserAttendance extends Model {
*/ */
private boolean userPresent; private boolean userPresent;
@Ignore
private static final PropertyInfo PI_userID = new PropertyInfo(); private static final PropertyInfo PI_userID = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userNickname = new PropertyInfo(); private static final PropertyInfo PI_userNickname = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userSurname1 = new PropertyInfo(); private static final PropertyInfo PI_userSurname1 = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userSurname2 = new PropertyInfo(); private static final PropertyInfo PI_userSurname2 = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userFirstname = new PropertyInfo(); private static final PropertyInfo PI_userFirstname = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userPhoto = new PropertyInfo(); private static final PropertyInfo PI_userPhoto = new PropertyInfo();
@Ignore
private static final PropertyInfo PI_userPresent = new PropertyInfo(); private static final PropertyInfo PI_userPresent = new PropertyInfo();
@Ignore
@SuppressWarnings("unused")
private static PropertyInfo[] PI_PROP_ARRAY = { private static PropertyInfo[] PI_PROP_ARRAY = {
PI_userID, PI_userID,
PI_userNickname, PI_userNickname,
@ -59,39 +85,12 @@ public class UserAttendance extends Model {
PI_userPresent PI_userPresent
}; };
public UserAttendance(long id) {
super(id);
}
/**
* Constructor.
*
* @param id User code.
* @param eventCode Event code.
* @param userPresent Flag for indicate if the user is present in the attendance.
*/
public UserAttendance(long id, int eventCode, boolean userPresent) { public UserAttendance(long id, int eventCode, boolean userPresent) {
super(id); super(id);
this.eventCode = eventCode; this.eventCode = eventCode;
this.userPresent = userPresent; this.userPresent = userPresent;
} }
public int getEventCode() {
return eventCode;
}
public void setEventCode(int eventCode) {
this.eventCode = eventCode;
}
public boolean isUserPresent() {
return userPresent;
}
public void setUserPresent(boolean userPresent) {
this.userPresent = userPresent;
}
public Object getProperty(int param) { public Object getProperty(int param) {
Object object = null; Object object = null;
switch (param) { switch (param) {
@ -106,9 +105,11 @@ public class UserAttendance extends Model {
return object; return object;
} }
public int getPropertyCount() { return PI_PROP_ARRAY.length; } public int getPropertyCount() {
return PI_PROP_ARRAY.length;
}
public void getPropertyInfo(int param, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo propertyInfo) { public void getPropertyInfo(int param, Hashtable arg1, PropertyInfo propertyInfo) {
switch (param) { switch (param) {
case 0: case 0:
propertyInfo.type = PropertyInfo.STRING_CLASS; propertyInfo.type = PropertyInfo.STRING_CLASS;
@ -152,11 +153,4 @@ public class UserAttendance extends Model {
} }
} }
@Override
public String toString() {
return "UserAttendance{" +
"eventCode=" + eventCode +
", userPresent=" + userPresent +
"} " + super.toString();
}
} }

View File

@ -21,15 +21,17 @@ package es.ugr.swad.swadroid.model;
import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.PropertyInfo;
import java.io.Serializable;
import java.util.Hashtable; import java.util.Hashtable;
import lombok.Data;
/** /**
* User data. * User data.
* *
* @author Rubén Martín Hidalgo * @author Rubén Martín Hidalgo
*/ */
public class UserFilter extends Model implements Serializable{ @Data
public class UserFilter extends Model {
/** /**
* User identifier. * User identifier.
*/ */
@ -59,17 +61,7 @@ public class UserFilter extends Model implements Serializable{
*/ */
private boolean selectedCheckbox; private boolean selectedCheckbox;
/** public UserFilter(String userNickname, String userSurname1, String userSurname2, String userFirstname, String userPhoto, int userCode, boolean selectedCheckbox) {
* Constructor.
* @param userNickname User identifier.
* @param userSurname1 User first surname.
* @param userSurname2 User last surname.
* @param userFirstname User name.
* @param userPhoto Full path where user's picture is stored.
* @param userCode Unique identifier for each user
* @param selectedCheckbox Is a receiver?.
*/
public UserFilter(String userNickname, String userSurname1, String userSurname2, String userFirstname, String userPhoto, int userCode, boolean selectedCheckbox){
this.userNickname = userNickname; this.userNickname = userNickname;
this.userSurname1 = userSurname1; this.userSurname1 = userSurname1;
this.userSurname2 = userSurname2; this.userSurname2 = userSurname2;
@ -79,132 +71,6 @@ public class UserFilter extends Model implements Serializable{
this.selectedCheckbox = selectedCheckbox; this.selectedCheckbox = selectedCheckbox;
} }
/**
* Gets user name.
*
* @return User name.
*/
public String getUserFirstname() {
return userFirstname;
}
/**
* Sets user name.
*
* @param userFirstname User name.
*/
public void setUserFirstname(String userFirstname) {
this.userFirstname = userFirstname;
}
/**
* Gets user identifier.
*
* @return User identifier.
*/
public String getUserNickname() {
return userNickname;
}
/**
* Sets user identifier.
*
* @param userNickname User identifier.
*/
public void setUserNickname(String userNickname) {
this.userNickname = userNickname;
}
/**
* Gets user first surname.
*
* @return User first surname.
*/
public String getUserSurname1() {
return userSurname1;
}
/**
* Sets user first surname.
*
* @param userSurname1 User first surname.
*/
public void setUserSurname1(String userSurname1) {
this.userSurname1 = userSurname1;
}
/**
* Gets user last surname.
*
* @return User last surname.
*/
public String getUserSurname2() {
return userSurname2;
}
/**
* Sets user last surname.
*
* @param userSurname2 User last surname.
*/
public void setUserSurname2(String userSurname2) {
this.userSurname2 = userSurname2;
}
/**
* Gets Full path where user's picture is stored.
*
* @return the userPhoto
*/
public String getUserPhoto() {
return userPhoto;
}
/**
* Sets Full path where user's picture is stored.
*
* @param userPhoto the userPhoto to set
*/
public void setUserPhoto(String userPhoto) {
this.userPhoto = userPhoto;
}
/**
* Gets users code.
*
* @return the userCode
*/
public int getUserCode() {
return userCode;
}
/**
* Sets user code.
*
* @param userCode the userCode to set
*/
public void setUserCode(int userCode) {
this.userCode = userCode;
}
/**
* Get if checkbox is selected.
*
* @return if checkbox is selected (true / false)
*/
public boolean getCheckbox() {
return selectedCheckbox;
}
/**
* Sets Full path where user's picture is stored.
*
* @param selected the checkbox is selected or not
*/
public void setCheckbox(boolean selected){
this.selectedCheckbox = selected;
}
@Override @Override
public Object getProperty(int index) { public Object getProperty(int index) {
return null; return null;
@ -217,11 +83,11 @@ public class UserFilter extends Model implements Serializable{
@Override @Override
public void setProperty(int index, Object value) { public void setProperty(int index, Object value) {
// No-op
} }
@Override @Override
public void getPropertyInfo(int index, Hashtable properties, PropertyInfo info) { public void getPropertyInfo(int index, Hashtable properties, PropertyInfo info) {
// No-op
} }
} }

View File

@ -58,7 +58,7 @@ import es.ugr.swad.swadroid.webservices.SOAPClient;
/** /**
* Superclass for encapsulate common behavior of all modules. * Superclass for encapsulate common behavior of all modules.
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public abstract class Module extends MenuActivity { public abstract class Module extends MenuActivity {
/** /**
@ -249,7 +249,7 @@ public abstract class Module extends MenuActivity {
webserviceClient = new SOAPClient(); webserviceClient = new SOAPClient();
} }
webserviceClient.setMETHOD_NAME(METHOD_NAME); webserviceClient.setMethodName(METHOD_NAME);
} }
webserviceClient.createRequest(); webserviceClient.createRequest();
@ -400,11 +400,6 @@ public abstract class Module extends MenuActivity {
error(errorMsg, e); error(errorMsg, e);
setResult(RESULT_CANCELED); setResult(RESULT_CANCELED);
// Launch database rollback
if (dbHelper.isDbInTransaction()) {
dbHelper.endTransaction(false);
}
onError(); onError();
} else { } else {
postConnect(); postConnect();

View File

@ -36,7 +36,7 @@ import es.ugr.swad.swadroid.webservices.SOAPClient;
* Module for create a new account * Module for create a new account
* @see <a href="https://openswad.org/ws/#createAccount">createAccount</a> * @see <a href="https://openswad.org/ws/#createAccount">createAccount</a>
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class CreateAccount extends Module { public class CreateAccount extends Module {
/** /**

View File

@ -20,9 +20,7 @@ import android.app.AlertDialog;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.graphics.Color; import android.graphics.Color;
import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import android.view.KeyEvent; import android.view.KeyEvent;
@ -37,21 +35,23 @@ import android.widget.Spinner;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import es.ugr.swad.swadroid.Constants; import es.ugr.swad.swadroid.Constants;
import es.ugr.swad.swadroid.gui.ProgressScreen;
import es.ugr.swad.swadroid.preferences.Preferences;
import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.R;
import es.ugr.swad.swadroid.gui.DialogFactory; import es.ugr.swad.swadroid.gui.DialogFactory;
import es.ugr.swad.swadroid.gui.ProgressScreen;
import es.ugr.swad.swadroid.preferences.Preferences;
import es.ugr.swad.swadroid.utils.Utils; import es.ugr.swad.swadroid.utils.Utils;
/** /**
* *
* @author Alejandro Alcalde <algui91@gmail.com> * @author Alejandro Alcalde <algui91@gmail.com>
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
* *
*/ */
public class CreateAccountActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { public class CreateAccountActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

View File

@ -31,9 +31,8 @@ import java.util.List;
import java.util.Vector; import java.util.Vector;
import es.ugr.swad.swadroid.Constants; import es.ugr.swad.swadroid.Constants;
import es.ugr.swad.swadroid.database.DataBaseHelper; import es.ugr.swad.swadroid.dao.CourseDao;
import es.ugr.swad.swadroid.model.Course; import es.ugr.swad.swadroid.model.Course;
import es.ugr.swad.swadroid.model.Model;
import es.ugr.swad.swadroid.modules.Module; import es.ugr.swad.swadroid.modules.Module;
import es.ugr.swad.swadroid.modules.login.Login; import es.ugr.swad.swadroid.modules.login.Login;
import es.ugr.swad.swadroid.webservices.SOAPClient; import es.ugr.swad.swadroid.webservices.SOAPClient;
@ -42,7 +41,7 @@ import es.ugr.swad.swadroid.webservices.SOAPClient;
* Courses module for get user's courses * Courses module for get user's courses
* @see <a href="https://openswad.org/ws/#getCourses">getCourses</a> * @see <a href="https://openswad.org/ws/#getCourses">getCourses</a>
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
* @author Antonio Aguilera Malagon <aguilerin@gmail.com> * @author Antonio Aguilera Malagon <aguilerin@gmail.com>
* @author Helena Rodriguez Gijon <hrgijon@gmail.com> * @author Helena Rodriguez Gijon <hrgijon@gmail.com>
*/ */
@ -64,6 +63,8 @@ public class Courses extends Module {
*/ */
private static String selectedCourseFullName; private static String selectedCourseFullName;
private CourseDao courseDao;
@Override @Override
protected void runConnection() { protected void runConnection() {
super.runConnection(); super.runConnection();
@ -81,6 +82,9 @@ public class Courses extends Module {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setMETHOD_NAME("getCourses"); setMETHOD_NAME("getCourses");
getSupportActionBar().hide(); getSupportActionBar().hide();
//Initialize DAOs
courseDao = db.getCourseDao();
} }
/* (non-Javadoc) /* (non-Javadoc)
@ -127,12 +131,10 @@ public class Courses extends Module {
if (result != null) { if (result != null) {
//Stores courses data returned by webservice response //Stores courses data returned by webservice response
List<Model> coursesDB = dbHelper.getAllRows(DataBaseHelper.DB_TABLE_COURSES); List<Course> coursesDB = courseDao.findAll();
List<Model> coursesSWAD = new ArrayList<>(); List<Course> coursesSWAD = new ArrayList<>();
List<Model> newCourses = new ArrayList<>();
List<Model> obsoleteCourses = new ArrayList<>();
ArrayList<?> res = new ArrayList<Object>((Vector<?>) result); ArrayList<?> res = new ArrayList<>((Vector<?>) result);
SoapObject soap = (SoapObject) res.get(1); SoapObject soap = (SoapObject) res.get(1);
int csSize = soap.getPropertyCount(); int csSize = soap.getPropertyCount();
for (int i = 0; i < csSize; i++) { for (int i = 0; i < csSize; i++) {
@ -143,39 +145,26 @@ public class Courses extends Module {
String fullName = pii.getProperty("courseFullName").toString(); String fullName = pii.getProperty("courseFullName").toString();
Course c = new Course(id, userRole, shortName, fullName); Course c = new Course(id, userRole, shortName, fullName);
coursesSWAD.add(c); coursesSWAD.add(c);
/*if(isDebuggable)
Log.d(TAG, c.toString());*/
} }
Log.i(TAG, "Retrieved " + csSize + " courses"); Log.i(TAG, "Retrieved " + csSize + " courses");
//Obtain old unregistered courses and modified courses //Obtain old unregistered courses and modified courses
obsoleteCourses.addAll(coursesDB); List<Course> obsoleteCourses = new ArrayList<>(coursesDB);
obsoleteCourses.removeAll(coursesSWAD); obsoleteCourses.removeAll(coursesSWAD);
//Obtain new registered courses //Obtain new registered courses
newCourses.addAll(coursesSWAD); List<Course> newCourses = new ArrayList<>(coursesSWAD);
newCourses.removeAll(coursesDB); newCourses.removeAll(coursesDB);
newCourses.removeAll(obsoleteCourses); newCourses.removeAll(obsoleteCourses);
//Delete old unregistered courses stuff //Delete old unregistered courses stuff
csSize = obsoleteCourses.size(); csSize = (int) courseDao.deleteCourses(obsoleteCourses);
for (int i = 0; i < csSize; i++) {
Course c = (Course) obsoleteCourses.get(i);
dbHelper.removeRow(DataBaseHelper.DB_TABLE_COURSES, c.getId());
}
Log.i(TAG, "Deleted " + csSize + " old courses"); Log.i(TAG, "Deleted " + csSize + " old courses");
//Insert new registered courses //Insert new registered courses
csSize = newCourses.size(); courseDao.insertCourses(newCourses);
for (int i = 0; i < csSize; i++) { Log.i(TAG, "Added " + newCourses.size() + " new courses");
Course c = (Course) newCourses.get(i);
dbHelper.insertCourse(c);
}
Log.i(TAG, "Added " + csSize + " new courses");
//Request finalized without errors //Request finalized without errors
setResult(RESULT_OK); setResult(RESULT_OK);
@ -195,7 +184,7 @@ public class Courses extends Module {
*/ */
@Override @Override
protected void onError() { protected void onError() {
// No-op
} }
/** /**
@ -205,7 +194,7 @@ public class Courses extends Module {
*/ */
public void clearCourses(Context context) { public void clearCourses(Context context) {
try { try {
dbHelper.emptyTable(DataBaseHelper.DB_TABLE_COURSES); courseDao.deleteAll();
} catch (Exception e) { } catch (Exception e) {
Log.e(TAG, e.getMessage(), e); Log.e(TAG, e.getMessage(), e);
} }
@ -228,21 +217,17 @@ public class Courses extends Module {
public static void setSelectedCourseShortName(String currentCourseShortName) { public static void setSelectedCourseShortName(String currentCourseShortName) {
selectedCourseShortName = currentCourseShortName; selectedCourseShortName = currentCourseShortName;
} }
public static void setSelectedCourseFullName(String currentCourseFullName) { public static void setSelectedCourseFullName(String currentCourseFullName) {
selectedCourseFullName = currentCourseFullName; selectedCourseFullName = currentCourseFullName;
} }
public static String getSelectedCourseShortName() { public static String getSelectedCourseShortName() {
return selectedCourseShortName; return selectedCourseShortName;
} }
public static String getSelectedCourseFullName() { public static String getSelectedCourseFullName() {
return selectedCourseFullName; return selectedCourseFullName;
} }
} }

View File

@ -47,7 +47,7 @@ import es.ugr.swad.swadroid.Constants;
* *
* @author Sergio Ropero Oliver. <sro0000@gmail.com> * @author Sergio Ropero Oliver. <sro0000@gmail.com>
* @author Helena Rodriguez Gijon <hrgijon@gmail.com> * @author Helena Rodriguez Gijon <hrgijon@gmail.com>
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
* @version 1.0 * @version 1.0
*/ */

View File

@ -34,7 +34,7 @@ import es.ugr.swad.swadroid.Constants;
/** /**
* Class for manage file downloads * Class for manage file downloads
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class DownloadFactory { public class DownloadFactory {
/** /**

View File

@ -59,7 +59,7 @@ import es.ugr.swad.swadroid.Constants;
* {@link #ACTION_NOTIFICATION_CLICKED} to appropriately handle when the user clicks on a running * {@link #ACTION_NOTIFICATION_CLICKED} to appropriately handle when the user clicks on a running
* download in a notification or from the downloads UI. * download in a notification or from the downloads UI.
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class DownloadManager { public class DownloadManager {
private static final String TAG = Constants.APP_TAG + " DownloadManager"; private static final String TAG = Constants.APP_TAG + " DownloadManager";

View File

@ -24,7 +24,7 @@ import android.provider.BaseColumns;
/** /**
* The Download Manager * The Download Manager
* *
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public final class Downloads { public final class Downloads {
/** /**

View File

@ -23,7 +23,6 @@ import android.annotation.TargetApi;
import android.app.Activity; import android.app.Activity;
import android.app.AlertDialog; import android.app.AlertDialog;
import android.content.ActivityNotFoundException; import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.content.res.Resources; import android.content.res.Resources;
@ -31,16 +30,10 @@ import android.graphics.Typeface;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Environment; import android.os.Environment;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import android.util.Log; import android.util.Log;
import android.view.KeyEvent; import android.view.KeyEvent;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView; import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener; import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter; import android.widget.ArrayAdapter;
import android.widget.GridView; import android.widget.GridView;
@ -48,6 +41,11 @@ import android.widget.Spinner;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import java.io.File; import java.io.File;
import java.net.URLConnection; import java.net.URLConnection;
import java.util.ArrayList; import java.util.ArrayList;
@ -56,6 +54,7 @@ import java.util.List;
import es.ugr.swad.swadroid.Constants; import es.ugr.swad.swadroid.Constants;
import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.R;
import es.ugr.swad.swadroid.dao.GroupDao;
import es.ugr.swad.swadroid.gui.FontManager; import es.ugr.swad.swadroid.gui.FontManager;
import es.ugr.swad.swadroid.gui.MenuActivity; import es.ugr.swad.swadroid.gui.MenuActivity;
import es.ugr.swad.swadroid.gui.ProgressScreen; import es.ugr.swad.swadroid.gui.ProgressScreen;
@ -74,7 +73,7 @@ import es.ugr.swad.swadroid.utils.Utils;
* the downloads of documents * the downloads of documents
* *
* @author Helena Rodriguez Gijon <hrgijon@gmail.com> * @author Helena Rodriguez Gijon <hrgijon@gmail.com>
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class DownloadsManager extends MenuActivity { public class DownloadsManager extends MenuActivity {
/** /**
@ -153,10 +152,15 @@ public class DownloadsManager extends MenuActivity {
*/ */
private boolean previousConnection = false; private boolean previousConnection = false;
/**
* DAO for groups
*/
private GroupDao groupDao;
private void init() { private void init() {
mProgressScreen.show(); mProgressScreen.show();
List<Group> allGroups = dbHelper.getGroups(Courses.getSelectedCourseCode()); List<Group> allGroups = groupDao.findGroupsCourseByCourseCode(Courses.getSelectedCourseCode()).groups;
int nGroups = allGroups.size(); int nGroups = allGroups.size();
if (!saveState) { if (!saveState) {
@ -205,6 +209,9 @@ public class DownloadsManager extends MenuActivity {
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
//Initialize DAOs
groupDao = db.getGroupDao();
if (savedInstanceState != null) { if (savedInstanceState != null) {
this.saveState = savedInstanceState.getBoolean("saveState", false); this.saveState = savedInstanceState.getBoolean("saveState", false);
if (saveState) { if (saveState) {
@ -236,30 +243,20 @@ public class DownloadsManager extends MenuActivity {
//Get Font Awesome typeface //Get Font Awesome typeface
iconFont = FontManager.getTypeface(this, FontManager.FONTAWESOME); iconFont = FontManager.getTypeface(this, FontManager.FONTAWESOME);
TextView homeButton = (TextView) this TextView homeButton = this
.findViewById(R.id.home_button); .findViewById(R.id.home_button);
homeButton.setOnClickListener((new OnClickListener() { homeButton.setOnClickListener((v -> {
@Override
public void onClick(View v) {
if (navigator != null) { if (navigator != null) {
updateView(navigator.goToRoot()); updateView(navigator.goToRoot());
} }
}
})); }));
TextView parentButton = (TextView) this TextView parentButton = this
.findViewById(R.id.parent_button); .findViewById(R.id.parent_button);
parentButton.setOnClickListener((new OnClickListener() { parentButton.setOnClickListener((v -> {
@Override
public void onClick(View v) {
if (navigator != null) { if (navigator != null) {
updateView(navigator.goToParentDirectory()); updateView(navigator.goToParentDirectory());
} }
}
})); }));
//Set Font Awesome typeface //Set Font Awesome typeface
@ -269,12 +266,10 @@ public class DownloadsManager extends MenuActivity {
downloadsAreaCode = getIntent().getIntExtra("downloadsAreaCode", downloadsAreaCode = getIntent().getIntExtra("downloadsAreaCode",
Constants.DOCUMENTS_AREA_CODE); Constants.DOCUMENTS_AREA_CODE);
messageText = (TextView) this.findViewById(R.id.messageText); messageText = this.findViewById(R.id.messageText);
grid = (GridView) this.findViewById(R.id.gridview); grid = this.findViewById(R.id.gridview);
grid.setOnItemClickListener((new OnItemClickListener() { grid.setOnItemClickListener(((parent, v, position, id) -> {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
DirectoryItem node = navigator.getDirectoryItem(position); DirectoryItem node = navigator.getDirectoryItem(position);
if (node.getFileCode() == -1) //it is a directory therefore navigates into it if (node.getFileCode() == -1) //it is a directory therefore navigates into it
@ -298,7 +293,6 @@ public class DownloadsManager extends MenuActivity {
} }
} }
} }
}
})); }));
View mDirectoryNavigatorView = findViewById(R.id.directoryNavigator); View mDirectoryNavigatorView = findViewById(R.id.directoryNavigator);
@ -390,11 +384,7 @@ public class DownloadsManager extends MenuActivity {
builder.setTitle(R.string.sdCardBusyTitle); builder.setTitle(R.string.sdCardBusyTitle);
builder.setMessage(R.string.sdCardBusy); builder.setMessage(R.string.sdCardBusy);
builder.setIcon(R.drawable.ic_dialog_alert); builder.setIcon(R.drawable.ic_dialog_alert);
builder.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { builder.setNeutralButton(android.R.string.ok, (dialog1, id) -> dialog1.dismiss());
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
dialog = builder.create(); dialog = builder.create();
dialog.show(); dialog.show();
} }
@ -408,7 +398,7 @@ public class DownloadsManager extends MenuActivity {
groupsRequested = true; groupsRequested = true;
myGroups = getFilteredGroups(); //only groups where the user is enrolled. myGroups = getFilteredGroups(); //only groups where the user is enrolled.
this.loadGroupsSpinner(myGroups); this.loadGroupsSpinner(myGroups);
if (myGroups.size() == 0) { if (myGroups.isEmpty()) {
requestDirectoryTree(); requestDirectoryTree();
} else { } else {
mProgressScreen.hide(); mProgressScreen.hide();
@ -496,7 +486,7 @@ public class DownloadsManager extends MenuActivity {
* This method set the grid of nodes visible and paints the directory tree in its root node * This method set the grid of nodes visible and paints the directory tree in its root node
*/ */
private void setMainView() { private void setMainView() {
currentPathText = (TextView) this.findViewById(R.id.path); currentPathText = this.findViewById(R.id.path);
ArrayList<DirectoryItem> items; ArrayList<DirectoryItem> items;
if (!(this.saveState && this.previousConnection)) { if (!(this.saveState && this.previousConnection)) {
@ -548,11 +538,11 @@ public class DownloadsManager extends MenuActivity {
* Get the list of the groups of the course with a documents zone to whom the user belongs * Get the list of the groups of the course with a documents zone to whom the user belongs
*/ */
private List<Group> getFilteredGroups() { private List<Group> getFilteredGroups() {
List<Group> currentGroups = dbHelper.getGroups(Courses.getSelectedCourseCode()); List<Group> currentGroups = groupDao.findGroupsCourseByCourseCode(Courses.getSelectedCourseCode()).groups;
//remove groups that do not have a file zone assigned //remove groups that do not have a file zone assigned
int j = 0; int j = 0;
while (j < currentGroups.size()) { while (j < currentGroups.size()) {
if (currentGroups.get(j).getDocumentsArea() != 0 && currentGroups.get(j).isMember()) if (currentGroups.get(j).getFileZones() != 0 && currentGroups.get(j).isMember())
++j; ++j;
else else
currentGroups.remove(j); currentGroups.remove(j);
@ -566,13 +556,13 @@ public class DownloadsManager extends MenuActivity {
private void loadGroupsSpinner(List<Group> currentGroups) { private void loadGroupsSpinner(List<Group> currentGroups) {
if (!currentGroups.isEmpty()) { //there are groups in the selected course, therefore the groups spinner should be loaded if (!currentGroups.isEmpty()) { //there are groups in the selected course, therefore the groups spinner should be loaded
Spinner groupsSpinner = (Spinner) this.findViewById(R.id.groupSpinner); Spinner groupsSpinner = this.findViewById(R.id.groupSpinner);
groupsSpinner.setVisibility(View.VISIBLE); groupsSpinner.setVisibility(View.VISIBLE);
ArrayList<String> spinnerNames = new ArrayList<>(currentGroups.size() + 1); ArrayList<String> spinnerNames = new ArrayList<>(currentGroups.size() + 1);
spinnerNames.add(getString(R.string.course) + "-" + Courses.getSelectedCourseShortName()); spinnerNames.add(getString(R.string.course) + "-" + Courses.getSelectedCourseShortName());
for (Group g : currentGroups) { for (Group g : currentGroups) {
GroupType gType = dbHelper.getGroupTypeFromGroup(g.getId()); GroupType gType = groupDao.findGroupsGroupTypeByGroupCode(g.getId()).groupType;
spinnerNames.add(getString(R.string.group) + "-" + gType.getGroupTypeName() + " " + g.getGroupName()); spinnerNames.add(getString(R.string.group) + "-" + gType.getGroupTypeName() + " " + g.getGroupName());
} }
@ -609,6 +599,7 @@ public class DownloadsManager extends MenuActivity {
@Override @Override
public void onNothingSelected(AdapterView<?> arg0) { public void onNothingSelected(AdapterView<?> arg0) {
// No-op
} }
} }
@ -769,16 +760,8 @@ public class DownloadsManager extends MenuActivity {
builder.setTitle(name); builder.setTitle(name);
builder.setMessage(message); builder.setMessage(message);
builder.setPositiveButton(R.string.downloadFileTitle, new DialogInterface.OnClickListener() { builder.setPositiveButton(R.string.downloadFileTitle, (dialog1, id) -> requestGetFile(code));
public void onClick(DialogInterface dialog, int id) { builder.setNegativeButton(R.string.cancelMsg, (dialog12, id) -> dialog12.dismiss());
requestGetFile(code);
}
});
builder.setNegativeButton(R.string.cancelMsg, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
dialog = builder.create(); dialog = builder.create();
return dialog; return dialog;

View File

@ -34,7 +34,7 @@ import es.ugr.swad.swadroid.R;
* Note that we are responsible for the deletion of the file when it is no longer needed. * Note that we are responsible for the deletion of the file when it is no longer needed.
* *
* @author Helena Rodriguez Gijon <hrgijon@gmail.com> * @author Helena Rodriguez Gijon <hrgijon@gmail.com>
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
* @author Victor Terron <vterron@iaa.es> * @author Victor Terron <vterron@iaa.es>
*/ */

View File

@ -30,8 +30,8 @@ import java.util.Vector;
import es.ugr.swad.swadroid.Constants; import es.ugr.swad.swadroid.Constants;
import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.R;
import es.ugr.swad.swadroid.model.Group; import es.ugr.swad.swadroid.model.Group;
import es.ugr.swad.swadroid.modules.login.Login;
import es.ugr.swad.swadroid.modules.Module; import es.ugr.swad.swadroid.modules.Module;
import es.ugr.swad.swadroid.modules.login.Login;
import es.ugr.swad.swadroid.webservices.SOAPClient; import es.ugr.swad.swadroid.webservices.SOAPClient;
/** /**

View File

@ -35,7 +35,7 @@ import es.ugr.swad.swadroid.gui.FontManager;
* Adapter to populate browser of files with the information received from SWAD * Adapter to populate browser of files with the information received from SWAD
* *
* @author Helena Rodriguez Gijon <hrgijon@gmail.com> * @author Helena Rodriguez Gijon <hrgijon@gmail.com>
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class NodeAdapter extends BaseAdapter { public class NodeAdapter extends BaseAdapter {

View File

@ -21,8 +21,6 @@ package es.ugr.swad.swadroid.modules.groups;
import android.content.Context; import android.content.Context;
import android.graphics.Color; import android.graphics.Color;
import android.graphics.Typeface; import android.graphics.Typeface;
import androidx.core.content.ContextCompat;
import androidx.collection.LongSparseArray;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.View.OnClickListener; import android.view.View.OnClickListener;
@ -33,15 +31,18 @@ import android.widget.LinearLayout;
import android.widget.RadioButton; import android.widget.RadioButton;
import android.widget.TextView; import android.widget.TextView;
import androidx.collection.LongSparseArray;
import androidx.core.content.ContextCompat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List;
import es.ugr.swad.swadroid.Constants; import es.ugr.swad.swadroid.Constants;
import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.R;
import es.ugr.swad.swadroid.gui.FontManager; import es.ugr.swad.swadroid.gui.FontManager;
import es.ugr.swad.swadroid.model.Group; import es.ugr.swad.swadroid.model.Group;
import es.ugr.swad.swadroid.model.GroupType; import es.ugr.swad.swadroid.model.GroupType;
import es.ugr.swad.swadroid.model.Model;
/** /**
* Adapter to populate with data an expandable list. * Adapter to populate with data an expandable list.
@ -49,19 +50,19 @@ import es.ugr.swad.swadroid.model.Model;
* There are two kind of layout: one for the groups and one for the children * There are two kind of layout: one for the groups and one for the children
* *
* @author Helena Rodriguez Gijon <hrgijon@gmail.com> * @author Helena Rodriguez Gijon <hrgijon@gmail.com>
* @author Juan Miguel Boyero Corral <juanmi1982@gmail.com> * @author Juan Miguel Boyero Corral <swadroid@gmail.com>
*/ */
public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter { public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
private LongSparseArray<ArrayList<Group>> children = null; private LongSparseArray<List<Group>> children;
private ArrayList<Model> groups = null; private final List<GroupType> groupTypes;
private final LongSparseArray<boolean[]> realMembership = new LongSparseArray<>(); private final LongSparseArray<boolean[]> realMembership = new LongSparseArray<>();
private static Typeface iconFont; private static Typeface iconFont;
private int role = -1; private final int role;
private int layoutGroup = 0; private final int layoutGroup;
private int layoutChild = 0; private final int layoutChild;
private static class GroupHolder { private static class GroupHolder {
TextView textViewGroupTypeName; TextView textViewGroupTypeName;
@ -81,10 +82,10 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
private final LayoutInflater mInflater; private final LayoutInflater mInflater;
private final Context context; private final Context context;
public EnrollmentExpandableListAdapter(Context context, ArrayList<Model> groups, LongSparseArray<ArrayList<Group>> children, int layoutGroup, int layoutChild, int currentRole) { public EnrollmentExpandableListAdapter(Context context, List<GroupType> groupTypes, LongSparseArray<List<Group>> children, int layoutGroup, int layoutChild, int currentRole) {
super(); super();
this.context = context; this.context = context;
this.groups = groups; this.groupTypes = groupTypes;
this.children = children; this.children = children;
this.layoutGroup = layoutGroup; this.layoutGroup = layoutGroup;
this.layoutChild = layoutChild; this.layoutChild = layoutChild;
@ -92,8 +93,8 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
//Initialize real inscription //Initialize real inscription
for (int i = 0; i < children.size(); i++) { for (int i = 0; i < children.size(); i++) {
Long groupTypeCode = children.keyAt(i); long groupTypeCode = children.keyAt(i);
ArrayList<Group> groupsChildren = children.get(groupTypeCode); List<Group> groupsChildren = children.get(groupTypeCode);
realMembership.put(groupTypeCode, new boolean[groupsChildren.size()]); realMembership.put(groupTypeCode, new boolean[groupsChildren.size()]);
} }
@ -106,14 +107,14 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
@Override @Override
public Object getChild(int groupPosition, int childPosition) { public Object getChild(int groupPosition, int childPosition) {
Long groupTypeCode = groups.get(groupPosition).getId(); long groupTypeCode = groupTypes.get(groupPosition).getId();
ArrayList<Group> children = this.children.get(groupTypeCode); List<Group> children = this.children.get(groupTypeCode);
return children.get(childPosition); return children.get(childPosition);
} }
@Override @Override
public long getChildId(int groupPosition, int childPosition) { public long getChildId(int groupPosition, int childPosition) {
return groupPosition * 10 + childPosition; return groupPosition * 10L + childPosition;
} }
@Override @Override
@ -136,10 +137,10 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
holder = (ChildHolder) convertView.getTag(); holder = (ChildHolder) convertView.getTag();
} }
Long groupTypeCode = groups.get(groupPosition).getId(); long groupTypeCode = groupTypes.get(groupPosition).getId();
int multiple = ((GroupType) groups.get(groupPosition)).getMultiple(); int multiple = ((GroupType) groupTypes.get(groupPosition)).getMultiple();
ArrayList<Group> children = this.children.get(groupTypeCode); List<Group> children = this.children.get(groupTypeCode);
Group group = children.get(childPosition); Group group = children.get(childPosition);
holder.linearLayout.setBackgroundColor(ContextCompat.getColor(context, android.R.color.white)); holder.linearLayout.setBackgroundColor(ContextCompat.getColor(context, android.R.color.white));
@ -147,7 +148,7 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
//Data from Group //Data from Group
String groupName = group.getGroupName(); String groupName = group.getGroupName();
int maxStudents = group.getMaxStudents(); int maxStudents = group.getMaxStudents();
int students = group.getCurrentStudents(); int students = group.getStudents();
int open = group.getOpen(); int open = group.getOpen();
int member = group.getMember(); int member = group.getMember();
@ -156,7 +157,7 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
holder.checkBox.setTag(g); holder.checkBox.setTag(g);
//if maxStudent == -1, there is not limit of students in this groups //if maxStudent == -1, there is not limit of students in this groups
boolean freeSpot = ((maxStudents == -1) || (group.getCurrentStudents() < maxStudents)); boolean freeSpot = ((maxStudents == -1) || (group.getStudents() < maxStudents));
if (open != 0) { if (open != 0) {
holder.imagePadlock.setText(R.string.fa_unlock); holder.imagePadlock.setText(R.string.fa_unlock);
@ -208,12 +209,12 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
holder.checkBox.setChecked(member != 0); holder.checkBox.setChecked(member != 0);
} }
holder.nStudentText.setText(context.getString(R.string.numStudent) + ": " + String.valueOf(students)); holder.nStudentText.setText(context.getString(R.string.numStudent) + ": " + students);
if (maxStudents != -1) { if (maxStudents != -1) {
int vacants = maxStudents - students; int vacants = maxStudents - students;
holder.maxStudentText.setText(context.getString(R.string.maxStudent) + ": " + String.valueOf(maxStudents)); holder.maxStudentText.setText(context.getString(R.string.maxStudent) + ": " + maxStudents);
holder.vacantsText.setText(context.getString(R.string.vacants) + ": " + String.valueOf(vacants)); holder.vacantsText.setText(context.getString(R.string.vacants) + ": " + vacants);
if (vacants == 0) { if (vacants == 0) {
holder.vacantsText.setTextColor(ContextCompat.getColor(context, R.color.sgi_salmon)); holder.vacantsText.setTextColor(ContextCompat.getColor(context, R.color.sgi_salmon));
holder.vacantsText.setTypeface(null, Typeface.BOLD); holder.vacantsText.setTypeface(null, Typeface.BOLD);
@ -231,19 +232,19 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
@Override @Override
public int getChildrenCount(int groupPosition) { public int getChildrenCount(int groupPosition) {
Long groupTypeCode = groups.get(groupPosition).getId(); long groupTypeCode = groupTypes.get(groupPosition).getId();
ArrayList<Group> children = this.children.get(groupTypeCode); List<Group> children = this.children.get(groupTypeCode);
return children.size(); return children.size();
} }
@Override @Override
public Object getGroup(int groupPosition) { public Object getGroup(int groupPosition) {
return groups.get(groupPosition); return groupTypes.get(groupPosition);
} }
@Override @Override
public int getGroupCount() { public int getGroupCount() {
return groups.size(); return groupTypes.size();
} }
@Override @Override
@ -259,14 +260,14 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
if (convertView == null) { if (convertView == null) {
convertView = mInflater.inflate(layoutGroup, parent, false); convertView = mInflater.inflate(layoutGroup, parent, false);
holder = new GroupHolder(); holder = new GroupHolder();
holder.textViewGroupTypeName = (TextView) convertView.findViewById(R.id.groupTypeText); holder.textViewGroupTypeName = convertView.findViewById(R.id.groupTypeText);
holder.openTimeText = (TextView) convertView.findViewById(R.id.openTimeText); holder.openTimeText = convertView.findViewById(R.id.openTimeText);
convertView.setTag(holder); convertView.setTag(holder);
} else { } else {
holder = (GroupHolder) convertView.getTag(); holder = (GroupHolder) convertView.getTag();
} }
GroupType groupType = (GroupType) groups.get(groupPosition); GroupType groupType = (GroupType) groupTypes.get(groupPosition);
holder.textViewGroupTypeName.setText(groupType.getGroupTypeName()); holder.textViewGroupTypeName.setText(groupType.getGroupTypeName());
long unixTime = groupType.getOpenTime(); long unixTime = groupType.getOpenTime();
@ -289,14 +290,14 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
@Override @Override
public boolean isChildSelectable(int groupPosition, int childPosition) { public boolean isChildSelectable(int groupPosition, int childPosition) {
Long groupTypeCode = groups.get(groupPosition).getId(); long groupTypeCode = groupTypes.get(groupPosition).getId();
ArrayList<Group> children = this.children.get(groupTypeCode); List<Group> children = this.children.get(groupTypeCode);
Group group = children.get(childPosition); Group group = children.get(childPosition);
int maxStudent = group.getMaxStudents(); int maxStudent = group.getMaxStudents();
boolean freeSpot = false; boolean freeSpot = false;
if (maxStudent != -1) { if (maxStudent != -1) {
if (group.getCurrentStudents() < maxStudent) if (group.getStudents() < maxStudent)
freeSpot = true; freeSpot = true;
} else { //if maxStudent == -1, there is not limit of students in this groups } else { //if maxStudent == -1, there is not limit of students in this groups
freeSpot = true; freeSpot = true;
@ -323,8 +324,8 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
if (multiple == 0 && previousCheckState == 0 && role != Constants.TEACHER_TYPE_CODE) {//unique enrollment. Only an option is checked. if (multiple == 0 && previousCheckState == 0 && role != Constants.TEACHER_TYPE_CODE) {//unique enrollment. Only an option is checked.
//If the group does not allow multiple enrollment and previously it was not checked, the rest of the groups should be unchecked. //If the group does not allow multiple enrollment and previously it was not checked, the rest of the groups should be unchecked.
Long groupTypeCode = groupType.getId(); long groupTypeCode = groupType.getId();
ArrayList<Group> children = this.children.get(groupTypeCode); List<Group> children = this.children.get(groupTypeCode);
for (int i = 0; i < children.size(); ++i) { for (int i = 0; i < children.size(); ++i) {
Group g = children.get(i); Group g = children.get(i);
if (i != childPosition) g.setMember(0); if (i != childPosition) g.setMember(0);
@ -337,7 +338,7 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
return result; return result;
} }
public void resetChildren(LongSparseArray<ArrayList<Group>> children) { public void resetChildren(LongSparseArray<List<Group>> children) {
this.children = children; this.children = children;
setRealInscription(); setRealInscription();
} }
@ -345,17 +346,17 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
public String getChosenGroupCodesAsString() { public String getChosenGroupCodesAsString() {
String groupCodes = ""; String groupCodes = "";
Long key; long key;
for (int i = 0; i < children.size(); i++) { for (int i = 0; i < children.size(); i++) {
key = children.keyAt(i); key = children.keyAt(i);
ArrayList<Group> child = children.get(key); List<Group> child = children.get(key);
Group g; Group g;
for (Group aChildren : child) { for (Group aChildren : child) {
g = aChildren; g = aChildren;
if (g.getMember() == 1) { if (g.getMember() == 1) {
long code = g.getId(); long code = g.getId();
if (groupCodes.compareTo("") != 0) groupCodes = if (groupCodes.compareTo("") != 0) groupCodes =
groupCodes.concat("," + String.valueOf(code)); groupCodes.concat("," + code);
else groupCodes = groupCodes.concat(String.valueOf(code)); else groupCodes = groupCodes.concat(String.valueOf(code));
} }
} }
@ -363,12 +364,12 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
return groupCodes; return groupCodes;
} }
public ArrayList<Long> getChosenGroupCodes() { public List<Long> getChosenGroupCodes() {
ArrayList<Long> groupCodes = new ArrayList<>(); List<Long> groupCodes = new ArrayList<>();
Long key; long key;
for (int i = 0; i < children.size(); i++) { for (int i = 0; i < children.size(); i++) {
key = children.keyAt(i); key = children.keyAt(i);
ArrayList<Group> child = children.get(key); List<Group> child = children.get(key);
Group g; Group g;
for (Group aChildren : child) { for (Group aChildren : child) {
g = aChildren; g = aChildren;
@ -383,8 +384,8 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
private void setRealInscription() { private void setRealInscription() {
for (int i = 0; i < children.size(); i++) { for (int i = 0; i < children.size(); i++) {
Long groupTypeCode = children.keyAt(i); long groupTypeCode = children.keyAt(i);
ArrayList<Group> childs = children.get(groupTypeCode); List<Group> childs = children.get(groupTypeCode);
Group g; Group g;
for (int k = 0; k < childs.size(); ++k) { for (int k = 0; k < childs.size(); ++k) {
g = childs.get(k); g = childs.get(k);
@ -393,17 +394,10 @@ public class EnrollmentExpandableListAdapter extends BaseExpandableListAdapter {
} }
} }
private OnClickListener checkListener = new OnClickListener() private final OnClickListener checkListener = v -> {
{
@Override
public void onClick(View v)
{
Group d = (Group) v.getTag(); Group d = (Group) v.getTag();
((CheckBox) v).setChecked(!d.isMember()); ((CheckBox) v).setChecked(!d.isMember());
d.setMember(d.isMember() ? 0:1); d.setMember(d.isMember() ? 0:1);
}
}; };
} }

Some files were not shown because too many files have changed in this diff Show More