├── .gitignore
├── .idea
├── .name
├── compiler.xml
├── copyright
│ └── profiles_settings.xml
├── encodings.xml
├── gradle.xml
├── misc.xml
├── modules.xml
├── runConfigurations.xml
└── vcs.xml
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── me
│ │ └── shalvah
│ │ └── dbtest
│ │ └── ApplicationTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── me
│ │ │ └── shalvah
│ │ │ └── dbtest
│ │ │ ├── CourseListActivity.java
│ │ │ ├── MainActivity.java
│ │ │ ├── StudentListActivity.java
│ │ │ └── TestSimpleContentProvider.java
│ └── res
│ │ ├── layout
│ │ ├── activity_course_list.xml
│ │ ├── activity_main.xml
│ │ ├── content_main.xml
│ │ └── course_list_item.xml
│ │ ├── menu
│ │ └── menu_list.xml
│ │ ├── mipmap-hdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxhdpi
│ │ └── ic_launcher.png
│ │ ├── mipmap-xxxhdpi
│ │ └── ic_launcher.png
│ │ ├── values-v21
│ │ └── styles.xml
│ │ ├── values-w820dp
│ │ └── dimens.xml
│ │ └── values
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── me
│ └── shalvah
│ └── dbtest
│ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── projectFilesBackup
└── .idea
│ └── workspace.xml
├── settings.gradle
└── simple-db
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
├── androidTest
└── java
│ └── me
│ └── shalvah
│ └── simpledb
│ └── ExampleInstrumentedTest.java
├── main
├── AndroidManifest.xml
├── java
│ └── me
│ │ └── shalvah
│ │ └── simpledb
│ │ ├── Column.java
│ │ ├── Schema.java
│ │ ├── SimpleContentProvider.java
│ │ └── Table.java
└── res
│ └── values
│ └── strings.xml
└── test
└── java
└── me
└── shalvah
└── simpledb
└── ExampleUnitTest.java
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/workspace.xml
5 | /.idea/libraries
6 | .DS_Store
7 | /build
8 | /captures
9 |
--------------------------------------------------------------------------------
/.idea/.name:
--------------------------------------------------------------------------------
1 | dbtest
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.idea/copyright/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 | 1.8
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
SimpleDB
2 |
3 | 
4 |
5 | SimpleDB is an Android library that makes working with SQLite databases reaaaally simple. The aim is to get your app up and running with a functional SQLite database within minutes (true) without you worrying about the internals, so you can focus on building a great app.
6 |
7 | You don't need to craft complex SQL statements anymore. All you need to do now is define your schema, and SimpleDB handles the rest!
8 |
9 | # Setup
10 | * Step 0: Add the dependency to your app's `build.gradle`
11 | ```
12 | compile 'me.shalvah.simpledb:simple-db:0.5.0'
13 | ```
14 |
15 | * Step 1: Create a class extending the `SimpleContentProvider`. This is your app's
16 | ContentProvider. Define your provider, database, and database version in a static block:
17 | names if you wish.
18 | ```
19 | public class MySimpleContentProvider extends SimpleContentProvider
20 | {
21 |
22 | static
23 | {
24 | DB_NAME = "mydb";
25 | PROVIDER_NAME = "me.shalvah.myapp.provider";
26 | DB_VERSION = 1;
27 | }
28 |
29 | }
30 | ```
31 |
32 | * Step 2: Implement the `setup()` function in your SimpleContentProvider. This is where you define your database schema.
33 |
34 | ```
35 | public void setup()
36 | {
37 | //create columns
38 | Column producerId = Column.id("_id");
39 | Column producerName = Column.text("name");
40 | Column producerAge = Column.integer("age");
41 |
42 | //create table and add columns
43 | Table producers = new Table("producers", producerName, producerAge);
44 |
45 | Column itemName = Column.text("name").unique();
46 | Column itemTypee = Column.text("type");
47 | Column itemPrice = Column.integer("price").notNull();
48 | Column itemProducedBy = Column.integer("produced_by").foreignKey("producers","id");
49 |
50 | Table items = new Table("courses", itemName, itemType, itemPrice, itemProducedBy);
51 |
52 | }
53 | ```
54 | Note that if a table has a column which is a foreign key to another, make sure you add the "independent" table first.
55 |
56 | * Step 3: You're good to go! Use the class you created as your ContentPovider.
57 |
58 | # Quickstart
59 | ## Creating columns
60 | ```
61 | Column.integer(columnName);
62 | Column.text(columnName);
63 | Column.real(columnName);
64 | Column.null(columnName);
65 | Column.blob(columnName);
66 | ```
67 | These methods all return Column objects, so you can chain the methods below to set additional properties
68 |
69 | ## Setting column properties
70 | If `col` is a `Column` object:
71 | ```
72 | col.notNull();
73 | col.primaryKey();
74 | col.id();
75 | col.unique();
76 | col.autoIncrement();
77 | col.foreignKey(referencesTableName, referencesColumnName);
78 | ```
79 | Again, these methods all return Column objects, so you can chain them to set additional properties
80 |
81 | ## Creating a Table
82 | ```
83 | Table t=new Table(tableName, col1, col2, col3, ...);
84 |
85 | Column[] cols=new Column[] {col1, col2, col3, ...};
86 | Table t=new Table(tableName, cols);```
87 | ```
88 |
89 | ## CRUD
90 | ```
91 | //insert a new item
92 | getContentResolver().insert(TestSimpleContentProvider.contentUri(tableName), values);
93 |
94 | //delete all items
95 | getContentResolver().delete(MySimpleContentProvider.contentUri("tableName"), null, null);
96 |
97 | //delete a particular item by id
98 | getContentResolver().delete(MySimpleContentProvider.contentUri
99 | (tableName + "/" + id),
100 | null,
101 | null);
102 | ```
103 |
104 | ## Using with a CursorLoader
105 | Loading data:
106 | ```private void fillData()
107 | {
108 | getLoaderManager().initLoader(0, null, this);
109 |
110 | sca = new SimpleCursorAdapter(this, R.layout.item_list_item, null,
111 | new String[]{"id", "name", "type", "price"},
112 | new int[] {R.id._id, R.id.name, R.id.type, R.id.price}, 0);
113 | mListView.setAdapter(sca);
114 | }
115 | ```
116 |
117 | Callbacks:
118 | ```
119 | @Override
120 | public Loader onCreateLoader(int id, Bundle args)
121 | {
122 | String[] projection = new String[]{"id", "name", "type", "price"};
123 | return new CursorLoader(this, TestSimpleContentProvider.contentUri
124 | ("items"), projection, null,
125 | null,
126 | null);
127 | }
128 | ```
129 |
130 | A simple test app using the library can be found [here] (https://github.com/Shalvah/dbtest).
131 |
132 | # Features
133 | * Foreign key support. Simpledb also automatically sets an fk column to be on-null if referencing an "_id" column; otherwise, you'll have to do that yourself or risk getting an SQL error
134 | * Content URIs: Simpledb automatically generates these.
135 |
136 | # Future features :)
137 | * Migrations: Currently, you have to manually increment the database version if you change your
138 | schema, and you lose all data (db is recreated)
139 |
140 | # Changelog (0.6.0)
141 | - Changed method namesto match Java convention
142 | - Removed auto adding of id column to prevent confusion
143 | - Removed requirement to call init() in setup()
144 |
145 | # Contributing
146 | All contributions are welcome! Starting with improvements to this doc! Correcting typos and feature additions equally welcome. You could also work on one of the "Future Features" above.
147 | If you discover an issue and don't have time to fix it, please add it in the issue tracker. Thanks!
148 | Please see the contribution guide
149 |
150 | Thanks for checking out Simpledb! I hope it does make your work simpler.
151 | Please star if you find it useful! Thanks!
152 |
153 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 23
5 | buildToolsVersion "23.0.3"
6 |
7 | defaultConfig {
8 | applicationId "me.shalvah.dbtest"
9 | minSdkVersion 17
10 | targetSdkVersion 23
11 | versionCode 1
12 | versionName "1.0"
13 | }
14 | buildTypes {
15 | release {
16 | minifyEnabled false
17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
18 | }
19 | }
20 | }
21 |
22 | dependencies {
23 | compile fileTree(include: ['*.jar'], dir: 'libs')
24 | testCompile 'junit:junit:4.12'
25 | compile 'com.android.support:appcompat-v7:23.2.1'
26 | compile 'com.android.support:design:23.2.1'
27 | compile 'me.shalvah.simpledb:simple-db:0.5.0'
28 | }
29 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in C:\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/app/src/androidTest/java/me/shalvah/dbtest/ApplicationTest.java:
--------------------------------------------------------------------------------
1 | package me.shalvah.dbtest;
2 |
3 | import android.app.Application;
4 | import android.test.ApplicationTestCase;
5 |
6 | /**
7 | * Testing Fundamentals
8 | */
9 | public class ApplicationTest extends ApplicationTestCase
10 | {
11 | public ApplicationTest()
12 | {
13 | super(Application.class);
14 | }
15 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
11 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
26 |
27 |
28 |
32 |
33 |
34 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/app/src/main/java/me/shalvah/dbtest/CourseListActivity.java:
--------------------------------------------------------------------------------
1 | package me.shalvah.dbtest;
2 |
3 | import android.app.LoaderManager;
4 | import android.content.ContentValues;
5 | import android.content.CursorLoader;
6 | import android.content.Loader;
7 | import android.database.Cursor;
8 | import android.os.Bundle;
9 | import android.support.v7.app.ActionBar;
10 | import android.support.v7.app.AppCompatActivity;
11 | import android.support.v7.widget.Toolbar;
12 | import android.view.View;
13 | import android.widget.EditText;
14 | import android.widget.ListView;
15 | import android.widget.SimpleCursorAdapter;
16 |
17 |
18 | public class CourseListActivity extends AppCompatActivity implements LoaderManager
19 | .LoaderCallbacks
20 | {
21 | private ListView lv;
22 | private SimpleCursorAdapter sca;
23 |
24 | @Override
25 | protected void onCreate(Bundle savedInstanceState)
26 | {
27 | super.onCreate(savedInstanceState);
28 | setContentView(R.layout.activity_course_list);
29 |
30 | Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
31 | setSupportActionBar(toolbar);
32 |
33 | ActionBar actionBar = getSupportActionBar();
34 | if (actionBar != null)
35 | {
36 | actionBar.setDisplayHomeAsUpEnabled(true);
37 | }
38 | lv = (ListView) findViewById(android.R.id.list);
39 | fillData();
40 | }
41 |
42 | private void fillData()
43 | {
44 | getLoaderManager().initLoader(0, null, this);
45 |
46 | sca = new SimpleCursorAdapter(this, R.layout.course_list_item, null,
47 | new String[]{TestSimpleContentProvider.COLUMN_ID,
48 | TestSimpleContentProvider.COLUMN_COURSES_CODE,
49 | TestSimpleContentProvider.COLUMN_COURSES_TITLE,
50 | TestSimpleContentProvider.COLUMN_COURSES_UNITS,
51 | TestSimpleContentProvider.COLUMN_COURSES_DESCRIPTION,
52 | TestSimpleContentProvider.COLUMN_COURSES_TOP_STUDENT
53 | }, new int[]
54 | {R.id._id, R.id.code, R.id.title, R.id.units, R.id.description, R.id.studentId}, 0);
55 | lv.setAdapter(sca);
56 |
57 | }
58 |
59 | @Override
60 | public Loader onCreateLoader(int id, Bundle args)
61 | {
62 | String[] projection = new String[]{TestSimpleContentProvider.COLUMN_ID,
63 | TestSimpleContentProvider.COLUMN_COURSES_CODE,
64 | TestSimpleContentProvider.COLUMN_COURSES_TITLE,
65 | TestSimpleContentProvider.COLUMN_COURSES_UNITS,
66 | TestSimpleContentProvider.COLUMN_COURSES_DESCRIPTION,
67 | TestSimpleContentProvider.COLUMN_COURSES_TOP_STUDENT};
68 | return new CursorLoader(this, TestSimpleContentProvider.contentUri
69 | (TestSimpleContentProvider.TABLE_COURSES), projection, null,
70 | null,
71 | null);
72 | }
73 |
74 | @Override
75 | public void onLoadFinished(Loader loader, Cursor data)
76 | {
77 | sca.swapCursor(data);
78 | }
79 |
80 | @Override
81 | public void onLoaderReset(Loader loader)
82 | {
83 | sca.swapCursor(null);
84 | }
85 |
86 | public void add(View view)
87 | {
88 | String text = ((EditText) findViewById(R.id.inputCourseET)).getText().toString();
89 | String[] data = text.split(",");
90 | ContentValues values = new ContentValues();
91 | try
92 | {
93 | values.put(TestSimpleContentProvider.COLUMN_COURSES_CODE, data[0]);
94 | values.put(TestSimpleContentProvider.COLUMN_COURSES_TITLE, data[1]);
95 | values.put(TestSimpleContentProvider.COLUMN_COURSES_UNITS, data[2]);
96 | values.put(TestSimpleContentProvider.COLUMN_COURSES_DESCRIPTION, data[3]);
97 | values.put(TestSimpleContentProvider.COLUMN_COURSES_TOP_STUDENT, data[4]);
98 | } catch (Exception e)
99 | {
100 | e.printStackTrace();
101 | }
102 | getContentResolver().insert(TestSimpleContentProvider.contentUri(TestSimpleContentProvider
103 | .TABLE_COURSES), values);
104 | ((EditText) findViewById(R.id.inputCourseET)).setText("");
105 | }
106 |
107 | public void clear(View view)
108 | {
109 | String text = ((EditText) findViewById(R.id.inputCourseET)).getText().toString();
110 | if (text.equalsIgnoreCase(""))
111 | {
112 | getContentResolver().delete(TestSimpleContentProvider.contentUri
113 | (TestSimpleContentProvider.TABLE_COURSES), null, null);
114 | } else
115 | {
116 | getContentResolver().delete(TestSimpleContentProvider.contentUri
117 | (TestSimpleContentProvider.TABLE_COURSES + "/" + text),
118 | null,
119 | null);
120 | ((EditText) findViewById(R.id.inputCourseET)).setText("");
121 | }
122 | }
123 | }
--------------------------------------------------------------------------------
/app/src/main/java/me/shalvah/dbtest/MainActivity.java:
--------------------------------------------------------------------------------
1 | package me.shalvah.dbtest;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.os.Bundle;
6 | import android.support.v7.app.AppCompatActivity;
7 | import android.support.v7.widget.Toolbar;
8 | import android.view.View;
9 |
10 | public class MainActivity extends AppCompatActivity
11 | {
12 |
13 | @Override
14 | protected void onCreate(Bundle savedInstanceState)
15 | {
16 | super.onCreate(savedInstanceState);
17 | setContentView(R.layout.activity_main);
18 | Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
19 | setSupportActionBar(toolbar);
20 |
21 | }
22 |
23 | public void launch(View view)
24 | {
25 | Context context = view.getContext();
26 | Intent intent;
27 | switch (view.getId())
28 | {
29 | case R.id.studentsBtn:
30 | intent = new Intent(context, StudentListActivity.class);
31 | break;
32 | default:
33 | intent = new Intent(context, CourseListActivity.class);
34 | break;
35 | }
36 | context.startActivity(intent);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/app/src/main/java/me/shalvah/dbtest/StudentListActivity.java:
--------------------------------------------------------------------------------
1 | package me.shalvah.dbtest;
2 |
3 | import android.app.LoaderManager;
4 | import android.content.ContentValues;
5 | import android.content.CursorLoader;
6 | import android.content.Loader;
7 | import android.database.Cursor;
8 | import android.os.Bundle;
9 | import android.support.v7.app.ActionBar;
10 | import android.support.v7.app.AppCompatActivity;
11 | import android.support.v7.widget.Toolbar;
12 | import android.view.View;
13 | import android.widget.EditText;
14 | import android.widget.ListView;
15 | import android.widget.SimpleCursorAdapter;
16 |
17 | public class StudentListActivity extends AppCompatActivity implements LoaderManager
18 | .LoaderCallbacks
19 | {
20 | private ListView lv;
21 | private SimpleCursorAdapter sca;
22 |
23 | @Override
24 | protected void onCreate(Bundle savedInstanceState)
25 | {
26 | super.onCreate(savedInstanceState);
27 | setContentView(R.layout.activity_course_list);
28 |
29 | Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
30 | setSupportActionBar(toolbar);
31 |
32 | ActionBar actionBar = getSupportActionBar();
33 | if (actionBar != null)
34 | {
35 | actionBar.setDisplayHomeAsUpEnabled(true);
36 | }
37 | lv = (ListView) findViewById(android.R.id.list);
38 | fillData();
39 | }
40 |
41 | private void fillData()
42 | {
43 | getLoaderManager().initLoader(0, null, this);
44 |
45 | sca = new SimpleCursorAdapter(this, R.layout.course_list_item, null,
46 | new String[]{TestSimpleContentProvider.COLUMN_ID,
47 | TestSimpleContentProvider.COLUMN_STUDENTS_NAME,
48 | TestSimpleContentProvider.COLUMN_STUDENTS_AGE
49 | }, new int[]
50 | {R.id._id, R.id.code, R.id.title}, 0);
51 | lv.setAdapter(sca);
52 |
53 | }
54 |
55 |
56 | @Override
57 | public Loader onCreateLoader(int id, Bundle args)
58 | {
59 | String[] projection = new String[]{TestSimpleContentProvider.COLUMN_ID,
60 | TestSimpleContentProvider.COLUMN_STUDENTS_NAME,
61 | TestSimpleContentProvider.COLUMN_STUDENTS_AGE};
62 | return new CursorLoader(this, TestSimpleContentProvider.contentUri
63 | (TestSimpleContentProvider.TABLE_STUDENTS), projection, null,
64 | null,
65 | null);
66 | }
67 |
68 | @Override
69 | public void onLoadFinished(Loader loader, Cursor data)
70 | {
71 | sca.swapCursor(data);
72 | }
73 |
74 | @Override
75 | public void onLoaderReset(Loader loader)
76 | {
77 | sca.swapCursor(null);
78 | }
79 |
80 |
81 | public void add(View view)
82 | {
83 | String text = ((EditText) findViewById(R.id.inputCourseET)).getText().toString();
84 | String[] data = text.split(",");
85 | ContentValues values = new ContentValues();
86 | try
87 | {
88 | values.put(TestSimpleContentProvider.COLUMN_STUDENTS_NAME, data[0]);
89 | values.put(TestSimpleContentProvider.COLUMN_STUDENTS_AGE, data[1]);
90 |
91 | } catch (Exception e)
92 | {
93 | e.printStackTrace();
94 | }
95 | getContentResolver().insert(TestSimpleContentProvider.contentUri(TestSimpleContentProvider
96 | .TABLE_STUDENTS), values);
97 | ((EditText) findViewById(R.id.inputCourseET)).setText("");
98 | }
99 |
100 | public void clear(View view)
101 | {
102 | String text = ((EditText) findViewById(R.id.inputCourseET)).getText().toString();
103 | if (text.equalsIgnoreCase(""))
104 | {
105 | getContentResolver().delete(TestSimpleContentProvider.contentUri
106 | (TestSimpleContentProvider.TABLE_STUDENTS), null, null);
107 | } else
108 | {
109 | getContentResolver().delete(TestSimpleContentProvider.contentUri
110 | (TestSimpleContentProvider.TABLE_STUDENTS + "/" + text),
111 | null,
112 | null);
113 | ((EditText) findViewById(R.id.inputCourseET)).setText("");
114 | }
115 | }
116 | }
117 |
--------------------------------------------------------------------------------
/app/src/main/java/me/shalvah/dbtest/TestSimpleContentProvider.java:
--------------------------------------------------------------------------------
1 | package me.shalvah.dbtest;
2 |
3 | import me.shalvah.simpledb.Column;
4 | import me.shalvah.simpledb.SimpleContentProvider;
5 | import me.shalvah.simpledb.Table;
6 |
7 |
8 | public class TestSimpleContentProvider extends SimpleContentProvider
9 | {
10 |
11 | public static final String DB_NAME = "dbtest";
12 |
13 | public static final String PROVIDER_NAME = "me.shalvah.dbtest.dprovider";
14 |
15 | public static final String TABLE_STUDENTS = "students";
16 | public static final String COLUMN_STUDENTS_NAME = "name";
17 | public static final String COLUMN_STUDENTS_AGE = "age";
18 |
19 | public static final String TABLE_COURSES = "courses";
20 | public static final String COLUMN_COURSES_CODE = "code";
21 | public static final String COLUMN_COURSES_TITLE = "title";
22 | public static final String COLUMN_COURSES_UNITS = "units";
23 | public static final String COLUMN_COURSES_DESCRIPTION = "description";
24 | public static final String COLUMN_COURSES_TOP_STUDENT = "top_student";
25 | private static final int DB_VERSION = 2;
26 |
27 | public void setup()
28 | {
29 | //create columns
30 | Column studentName = Column.Text(COLUMN_STUDENTS_NAME);
31 | Column studentAge = Column.Integer(COLUMN_STUDENTS_AGE);
32 |
33 | //create table and add columns
34 | Table students = new Table(TABLE_STUDENTS, studentName, studentAge);
35 |
36 | Column courseCode = Column.Text(COLUMN_COURSES_CODE);
37 | Column courseTitle = Column.Text(COLUMN_COURSES_TITLE);
38 | Column courseUnits = Column.Integer(COLUMN_COURSES_UNITS);
39 |
40 | Table courses = new Table(TABLE_COURSES, courseTitle, courseCode, courseUnits);
41 |
42 | //you can set additional properties
43 | Column courseDesc = Column.Text(COLUMN_COURSES_DESCRIPTION)
44 | .notNull();
45 | Column courseTopStudent = Column.Text(COLUMN_COURSES_TOP_STUDENT)
46 | .foreignKey(TABLE_STUDENTS, COLUMN_ID);
47 |
48 | //add a column to the table
49 | courses.add(courseDesc);
50 | courses.add(courseTopStudent);
51 |
52 | init(PROVIDER_NAME, DB_NAME, DB_VERSION, students, courses);
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_course_list.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
12 |
16 |
20 |
25 |
30 |
31 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
15 |
16 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/content_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
25 |
26 |
33 |
34 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/course_list_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
12 |
16 |
17 |
20 |
21 |
24 |
25 |
28 |
29 |
32 |
33 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/app/src/main/res/menu/menu_list.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shalvah/simple-db/284a6e847ffea16b07a845a1922f9f115402c007/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shalvah/simple-db/284a6e847ffea16b07a845a1922f9f115402c007/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shalvah/simple-db/284a6e847ffea16b07a845a1922f9f115402c007/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shalvah/simple-db/284a6e847ffea16b07a845a1922f9f115402c007/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shalvah/simple-db/284a6e847ffea16b07a845a1922f9f115402c007/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/values-v21/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values-w820dp/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 64dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/dimens.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 16dp
4 | 16dp
5 | 16dp
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | dbtest
3 | Settings
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/app/src/test/java/me/shalvah/dbtest/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package me.shalvah.dbtest;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * To work on unit tests, switch the Test Artifact in the Build Variants view.
9 | */
10 | public class ExampleUnitTest
11 | {
12 | @Test
13 | public void addition_isCorrect() throws Exception
14 | {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | configurations {
3 | }
4 |
5 | buildscript {
6 | repositories {
7 | jcenter()
8 | }
9 | dependencies {
10 | classpath 'com.android.tools.build:gradle:2.3.0'
11 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.4'
12 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1'
13 |
14 | // NOTE: Do not place your application dependencies here; they belong
15 | // in the individual module build.gradle files
16 | }
17 | }
18 |
19 | allprojects {
20 | repositories {
21 | jcenter()
22 | maven {
23 | url "http://dl.bintray.com/shalvah/maven"
24 | }
25 | }
26 | }
27 |
28 | task clean(type: Delete) {
29 | delete rootProject.buildDir
30 | }
31 |
32 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shalvah/simple-db/284a6e847ffea16b07a845a1922f9f115402c007/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Mar 03 13:52:24 WAT 2017
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/simple-db/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/simple-db/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | ext {
4 | bintrayRepo = 'maven'
5 | bintrayName = 'simple-db'
6 |
7 | publishedGroupId = 'me.shalvah.simpledb'
8 | libraryName = 'simple-db'
9 | artifact = 'simple-db'
10 |
11 | libraryDescription = 'An Android library to simplify working with SQLite databases'
12 |
13 | siteUrl = 'https://github.com/Shalvah/SimpleDB'
14 | gitUrl = 'https://github.com/Shalvah/SimpleDB.git'
15 |
16 | libraryVersion = '0.5.0'
17 |
18 | developerId = 'shalvah'
19 | developerName = 'Shalvah Adebayo'
20 | developerEmail = 'shalvah.adebayo@gmail.com'
21 |
22 | licenseName = 'The Apache Software License, Version 2.0'
23 | licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
24 | allLicenses = ["Apache-2.0"]
25 | }
26 |
27 | android {
28 | compileSdkVersion 23
29 | buildToolsVersion "23.0.3"
30 |
31 | defaultConfig {
32 | minSdkVersion 8
33 | targetSdkVersion 23
34 | versionCode 1
35 | versionName "1.0"
36 |
37 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
38 |
39 | }
40 | buildTypes {
41 | release {
42 | minifyEnabled false
43 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
44 | }
45 | }
46 | }
47 |
48 | dependencies {
49 | compile 'com.android.support:support-annotations:25.0.1'
50 | compile fileTree(dir: 'libs', include: ['*.jar'])
51 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
52 | exclude group: 'com.android.support', module: 'support-annotations'
53 | })
54 | compile 'com.android.support:appcompat-v7:23.0.1'
55 | testCompile 'junit:junit:4.12'
56 | }
57 |
58 | //bintray init
59 |
60 | apply plugin: 'com.github.dcendents.android-maven'
61 |
62 | group = publishedGroupId // Maven Group ID for the artifact
63 |
64 | install {
65 | repositories.mavenInstaller {
66 | // This generates POM.xml with proper parameters
67 | pom {
68 | project {
69 | packaging 'aar'
70 | groupId publishedGroupId
71 | artifactId artifact
72 |
73 | // Add your description here
74 | name libraryName
75 | description libraryDescription
76 |
77 | // Set your license
78 | licenses {
79 | license {
80 | name licenseName
81 | url licenseUrl
82 | }
83 | }
84 | developers {
85 | developer {
86 | id developerId
87 | name developerName
88 | email developerEmail
89 | }
90 | }
91 | }
92 | }
93 | }
94 | }
95 |
96 | // bintray do
97 |
98 | apply plugin: 'com.jfrog.bintray'
99 |
100 | version = libraryVersion
101 |
102 | task sourcesJar(type: Jar) {
103 | from android.sourceSets.main.java.srcDirs
104 | classifier = 'sources'
105 | }
106 |
107 | task javadoc(type: Javadoc) {
108 | source = android.sourceSets.main.java.srcDirs
109 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
110 | }
111 |
112 | task javadocJar(type: Jar, dependsOn: javadoc) {
113 | classifier = 'javadoc'
114 | from javadoc.destinationDir
115 | }
116 |
117 | artifacts {
118 | archives javadocJar
119 | archives sourcesJar
120 | }
121 |
122 | // Bintray
123 | Properties properties = new Properties()
124 | properties.load(project.rootProject.file('local.properties').newDataInputStream())
125 |
126 | bintray {
127 | user = properties.getProperty("bintray.user")
128 | key = properties.getProperty("bintray.apikey")
129 |
130 | configurations = ['archives']
131 | pkg {
132 | repo = bintrayRepo
133 | name = bintrayName
134 | desc = libraryDescription
135 | licenses = allLicenses
136 | publish = true
137 | publicDownloadNumbers = true
138 | version {
139 | desc = libraryDescription
140 | }
141 | }
142 | }
143 |
144 |
--------------------------------------------------------------------------------
/simple-db/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in C:\Android\sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
--------------------------------------------------------------------------------
/simple-db/src/androidTest/java/me/shalvah/simpledb/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package me.shalvah.simpledb;
2 |
3 | import android.content.Context;
4 | import android.support.test.InstrumentationRegistry;
5 | import android.support.test.runner.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest
19 | {
20 | @Test
21 | public void useAppContext() throws Exception
22 | {
23 | // Context of the app under test.
24 | Context appContext = InstrumentationRegistry.getTargetContext();
25 |
26 | assertEquals("me.shalvah.simpledb.test", appContext.getPackageName());
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/simple-db/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/simple-db/src/main/java/me/shalvah/simpledb/Column.java:
--------------------------------------------------------------------------------
1 | package me.shalvah.simpledb;
2 |
3 |
4 | /**
5 | * Models a column in a table in the database
6 | */
7 | public class Column
8 | {
9 | /**
10 | * The name of the column.
11 | * By convention, this is automatically converted to lowercase
12 | */
13 | private String name;
14 |
15 | /**
16 | * The data type of the column.
17 | * By convention, this is automatically converted to uppercase
18 | */
19 | private String dataType;
20 |
21 | /**
22 | * If the column is a primary key. By default, this is FALSE
23 | */
24 | private boolean primaryKey;
25 |
26 | /**
27 | * If the column value is automatically incremented. By default, this is FALSE
28 | */
29 | private boolean autoIncrement;
30 |
31 | /**
32 | * If the column value is to be unique.
33 | * By default, this is FALSE
34 | */
35 | private boolean unique;
36 |
37 | /**
38 | * If the column value is allowed to be null.
39 | * By default, this is TRUE
40 | */
41 | private boolean nullable=true;
42 |
43 | /**
44 | * If the column value is a foreign key.By default, this is FALSE
45 | */
46 | private boolean foreignKey;
47 |
48 | /**
49 | * The name of the table referenced by this column (if this column is a foreign key).
50 | *
51 | */
52 | private String referencesTable;
53 |
54 | /**
55 | * The name of the column in @link referencesTable referenced by this column (if this column
56 | * is a foreign key).
57 | */
58 | private String referencesColumn;
59 |
60 | /**
61 | * The name of the table to which this column belongs
62 | */
63 | private String table;
64 |
65 |
66 | /**
67 | * Adds a new column to the schema
68 | *
69 | * @param name The name of the column
70 | * @param type The data type of the column
71 | */
72 | public Column(String name, String type)
73 | {
74 | this.name = name.toLowerCase();
75 | this.dataType = type.toUpperCase();
76 | }
77 |
78 | ////////////////////////////////////////////////////////
79 | //
80 | //----------------------Setters----------------------//
81 | //
82 | ///////////////////////////////////////////////////////
83 |
84 | /**
85 | * Create a column of type INTEGER
86 | *
87 | * @param name the column name
88 | * @return the column
89 | */
90 | public static Column integer(String name)
91 | {
92 | return new Column(name, "INTEGER");
93 | }
94 |
95 | /**
96 | * Create a column of type TEXT
97 | *
98 | * @param name the column name
99 | * @return the column
100 | */
101 | public static Column text(String name)
102 | {
103 | return new Column(name, "TEXT");
104 | }
105 |
106 | /**
107 | * Create a column of type BLOB
108 | *
109 | * @param name the column name
110 | * @return the column
111 | */
112 | public static Column blob(String name)
113 | {
114 | return new Column(name, "BLOB");
115 | }
116 |
117 | /**
118 | * Create a column of type REAL
119 | *
120 | * @param name the column name
121 | * @return the column
122 | */
123 | public static Column real(String name)
124 | {
125 | return new Column(name, "REAL");
126 | }
127 |
128 | /**
129 | * Create a column of type NuLL
130 | *
131 | * @param name the column name
132 | * @return the column
133 | */
134 | public static Column null(String name)
135 | {
136 | return new Column(name, "NULL");
137 | }
138 |
139 | /**
140 | * Create an id column
141 | *
142 | * @param name the column name
143 | * @return the column
144 | */
145 | public static Column id(String name)
146 |
147 | {
148 | return new Column(name, "INTEGER").primaryKey().autoIncrement();
149 | }
150 |
151 | ////////////////////////////////////////////////////////
152 | //
153 | //----------------------Getters----------------------//
154 | //
155 | ///////////////////////////////////////////////////////
156 |
157 | /**
158 | * Sets a column as a primary key
159 | *
160 | * @return the column
161 | */
162 | public Column primaryKey()
163 | {
164 | this.primaryKey = true;
165 | this.nullable = false;
166 | return this;
167 | }
168 |
169 | /**
170 | * Sets a column ro auto-increment
171 | *
172 | * @return the column
173 | */
174 | public Column autoIncrement()
175 | {
176 | this.autoIncrement = true;
177 | return this;
178 | }
179 |
180 | /**
181 | * Sets a column value as a unique index
182 | *
183 | * @return the column
184 | */
185 | public Column unique()
186 | {
187 | this.unique = true;
188 | return this;
189 | }
190 |
191 | /**
192 | * Sets a column as a foreign key
193 | * Also sets the column and table which the column references (if column is a foreign key)
194 | *
195 | * @return the column
196 | */
197 | public Column foreignKey(String referencesTable, String referencesColumn)
198 | {
199 | this.foreignKey = true;
200 | this.referencesTable = referencesTable;
201 | this.referencesColumn = referencesColumn;
202 | if(referencesColumn.equalsIgnoreCase("_id"))
203 | {
204 | this.nullable=false;
205 | }
206 | return this;
207 | }
208 |
209 | /**
210 | * Sets a column as non-null
211 | *
212 | * @return the column
213 | */
214 | public Column notNull()
215 | {
216 | this.nullable = false;
217 | return this;
218 | }
219 |
220 | /**
221 | * Sets the table to which the column belongs
222 | *
223 | * @param tableName The name of the table
224 | * @return the column
225 | */
226 | public Column belongsTo(String tableName)
227 | {
228 | this.table = tableName;
229 | return this;
230 | }
231 |
232 | ////////////////////////////////////////////////////////
233 |
234 | /**
235 | * Gets the name of the column
236 | *
237 | * @return the name of the column
238 | */
239 | public String name()
240 | {
241 | return name;
242 | }
243 |
244 | /**
245 | * Gets the type of the column
246 | *
247 | * @return the data type of the column
248 | */
249 | public String type()
250 | {
251 | return this.dataType;
252 | }
253 |
254 | /**
255 | * If the column is a foreign key index
256 | *
257 | * @return true if the column is a foreign key, false otherwise
258 | */
259 | public boolean isForeignKey()
260 | {
261 | return foreignKey;
262 | }
263 |
264 | /**
265 | * Gets the table to which the column belongs
266 | *
267 | * @return the name of the table of the column
268 | */
269 | public String belongsTo()
270 | {
271 | return this.table;
272 | }
273 |
274 | /**
275 | * Gets the table and column which the column refernces (if the column is a foreign key)
276 | *
277 | * @return string array with first elemsnt as the name of the referenced table and second the
278 | * name* of the referenced column
279 | */
280 | public String[] references()
281 | {
282 | return new String[]{this.referencesTable, this.referencesColumn};
283 | }
284 |
285 | /**
286 | * Generates SQLite CREATE statement for the column.
287 | * Only to be called by its containing table
288 | *
289 | * @return the create statement
290 | */
291 | public String create()
292 | {
293 | String nullValue = (this.nullable) ? ("NULL") : ("NOT NULL");
294 | String pkValue= (this.primaryKey) ? ("PRIMARY KEY") : ("");
295 | String aiValue= (this.autoIncrement) ? ("AUTOINCREMENT") : ("");
296 | String uniqueValue=(this.unique) ? ("UNIQUE") : ("");
297 |
298 |
299 | String createStatement = this.name + " "
300 | + this.dataType + " "
301 | + nullValue + " "
302 | + pkValue + " "
303 | + aiValue + " "
304 | + uniqueValue;
305 |
306 | return createStatement;
307 | }
308 |
309 | /**
310 | * Generates the foreign key portion of the create statement of this column
311 | *
312 | * @return "FOREIGN KEY(columnName) REFERENCES tableName(columnName)" if the column is a
313 | * foreign key; otherwise an empty string
314 | */
315 | public String foreignKeyStatement()
316 | {
317 | if (foreignKey)
318 | {
319 | return "FOREIGN KEY (" + name + ") "
320 | + "REFERENCES " + referencesTable
321 | + "(" + referencesColumn + ")";
322 | } else
323 | {
324 | return "";
325 | }
326 | }
327 |
328 | }
329 |
--------------------------------------------------------------------------------
/simple-db/src/main/java/me/shalvah/simpledb/Schema.java:
--------------------------------------------------------------------------------
1 | package me.shalvah.simpledb;
2 |
3 |
4 | import android.content.Context;
5 | import android.database.sqlite.SQLiteDatabase;
6 | import android.database.sqlite.SQLiteOpenHelper;
7 |
8 | import java.util.ArrayList;
9 | import java.util.LinkedHashMap;
10 |
11 | /**
12 | * Models the database concept while extending the SQLiteOpenHelper
13 | *
14 | * @author Shalvah Adebayo shalvah@shalvah.me
15 | */
16 | public class Schema extends SQLiteOpenHelper
17 | {
18 | /**
19 | * The tables in the database
20 | */
21 | private LinkedHashMap tables;
22 |
23 | /**
24 | * List of drop statements
25 | */
26 | private ArrayList dropStatements;
27 |
28 | /**
29 | * Create a new database and add tables
30 | *
31 | * @param context The application context
32 | * @param dbName The database name
33 | * @param dbVersion The database version
34 | * @param dbTables array of tales to be added
35 | */
36 | public Schema(Context context, String dbName, int dbVersion, Table... dbTables)
37 | {
38 | super(context, dbName, null, dbVersion);
39 | tables = new LinkedHashMap();
40 | dropStatements = new ArrayList<>();
41 | for (Table t :
42 | dbTables)
43 | {
44 | this.tables.put(t.name(), t);
45 | this.dropStatements.add(t.drop());
46 | }
47 | }
48 |
49 | /**
50 | * Create an SQLite Database
51 | * Should be called only after initializing tables and columns
52 | *
53 | * @return the SQLite database
54 | */
55 | public SQLiteDatabase create()
56 | {
57 | return this.getWritableDatabase();
58 | }
59 |
60 | @Override
61 | public void onCreate(SQLiteDatabase db)
62 | {
63 | for (Table table : tables.values())
64 | {
65 | db.execSQL(table.create());
66 | }
67 | }
68 |
69 | @Override
70 | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
71 | {
72 | for (String dropStatement : dropStatements)
73 | {
74 | db.execSQL(dropStatement);
75 | }
76 | onCreate(db);
77 | }
78 |
79 | /**
80 | * Gets a table, given a name
81 | *
82 | * @param tableName the name of the table
83 | * @return a Table object of that table name if it exists in the schema; otherwise an
84 | * Exception is thrown
85 | */
86 | public Table table(String tableName)
87 | {
88 | if (!this.tables.containsKey(tableName))
89 | throw new IllegalArgumentException("Table doesn't exist") ;
90 | return this.tables.get(tableName);
91 | }
92 |
93 | }
94 |
--------------------------------------------------------------------------------
/simple-db/src/main/java/me/shalvah/simpledb/SimpleContentProvider.java:
--------------------------------------------------------------------------------
1 | package me.shalvah.simpledb;
2 |
3 | import android.content.ContentProvider;
4 | import android.content.ContentValues;
5 | import android.content.UriMatcher;
6 | import android.database.Cursor;
7 | import android.database.sqlite.SQLiteDatabase;
8 | import android.database.sqlite.SQLiteQueryBuilder;
9 | import android.net.Uri;
10 | import android.support.annotation.Nullable;
11 | import android.text.TextUtils;
12 |
13 | import java.util.ArrayList;
14 | import java.util.Arrays;
15 | import java.util.HashMap;
16 | import java.util.HashSet;
17 |
18 | /**
19 | * ContentProvider with methods and variables implemented
20 | */
21 | public abstract class SimpleContentProvider extends ContentProvider
22 | {
23 | /**
24 | * The tables in the db
25 | */
26 | public static Table[] tables;
27 |
28 | /**
29 | * The provider name
30 | */
31 | protected static String PROVIDER_NAME = "me.shalvah.simpledb.dataprovider";
32 |
33 | /**
34 | * The provider name
35 | */
36 | protected static String DB_NAME = "mydb";
37 |
38 | /**
39 | * The provider name
40 | */
41 | protected static int DB_VERSION = 1;
42 |
43 | /**
44 | * Uri Matcher used to match content uris
45 | */
46 | private static final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
47 |
48 | /**
49 | * Base paths for tables in the schema
50 | */
51 | public static ArrayList BASE_PATH = new ArrayList<>();
52 |
53 | /**
54 | * Content uris for tables in the schema
55 | */
56 | public static ArrayList CONTENT_URI = new ArrayList<>();
57 |
58 | /**
59 | * Integer constants used to match uris for different tables in the schema and their
60 | * corresponding "_ID" address
61 | */
62 | public static HashMap uriMatcherStrings = new HashMap();
63 |
64 | /**
65 | * The database schema model
66 | */
67 | public static Schema db;
68 |
69 | /**
70 | * The actual SQLite database
71 | */
72 | private static SQLiteDatabase sqldb;
73 |
74 | /**
75 | * Gets the content uri generated for a given string.
76 | *
77 | * @param tableName either the name of the table ("items") or the table name followed by a
78 | * slash, then an id ("items/3")
79 | * @return the uri for the reource
80 | */
81 | public static Uri contentUri(String tableName)
82 | {
83 | if (tableName.contains("/"))
84 | {
85 | String realName = tableName.substring(0, tableName.indexOf("/"));
86 | String id = tableName.substring(tableName.indexOf("/") + 1);
87 | return Uri.parse("content://" + PROVIDER_NAME + "/" +
88 | realName + "/" + id);
89 | }
90 | return Uri.parse("content://" + PROVIDER_NAME + "/" +
91 | tableName);
92 | }
93 |
94 | /**
95 | * Creates the database schema and sets up base paths, content uris and uri matching
96 | *
97 | * @param providerName the package name of the content provider
98 | * @param dbName the desired name of the database
99 | * @param dbVersion the version number of the database. Increment this whenever you make
100 | * changes to your schema (change tables or columns)
101 | * @param tables the tables to be created in the database
102 | */
103 | public void init(String providerName, String dbName, int dbVersion, Table... tables)
104 | {
105 | //init schema
106 | db = new Schema(getContext(), dbName, dbVersion, tables);
107 |
108 | //setup base paths and content uris
109 | for (int i = 0; i < tables.length; i++)
110 | {
111 | Table t = tables[i];
112 | BASE_PATH.add(t.name());
113 | CONTENT_URI.add(Uri.parse("content://" + PROVIDER_NAME + "/" + BASE_PATH.get(i)));
114 | uriMatcherStrings.put(t.name(), (int) Math.pow(10, i));
115 | uriMatcherStrings.put(t.name() + "_ID", ((int) Math.pow(10, i)) * 2);
116 | }
117 |
118 | //setup uri matcher
119 | for (int i = 0; i < BASE_PATH.size(); i++)
120 | {
121 | String tname = BASE_PATH.get(i);
122 | matcher.addURI(PROVIDER_NAME, tname, uriMatcherStrings.get(tname));
123 | matcher.addURI(PROVIDER_NAME, tname + "/#", uriMatcherStrings.get(tname + "_ID"));
124 | }
125 | }
126 |
127 | @Override
128 | public boolean onCreate()
129 | {
130 | //all columns and tables must be created before this is run!
131 | setup();
132 | init(PROVIDER_NAME, DB_NAME, DB_VERSION, tables);
133 | sqldb = db.create();
134 | return (sqldb != null);
135 | }
136 |
137 | /**
138 | * Define a schema for your database in terms of tables and columns
139 | */
140 | abstract public void setup();
141 |
142 | @Nullable
143 | @Override
144 | public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
145 | {
146 | SQLiteQueryBuilder qBuild = new SQLiteQueryBuilder();
147 |
148 | int uriType = matcher.match(uri);
149 | try
150 | {
151 | checkColumns(projection, uriType);
152 | } catch (IllegalArgumentException e)
153 | {
154 | e.printStackTrace();
155 | }
156 |
157 | for (String s :
158 | uriMatcherStrings.keySet())
159 | {
160 | if (uriMatcherStrings.get(s).equals(uriType))
161 | {
162 | qBuild.setTables(s);
163 | if (s.endsWith("_ID"))
164 | {
165 | qBuild.appendWhere("_id" + "="
166 | + uri.getLastPathSegment());
167 | }
168 | Cursor cursor = qBuild.query(sqldb, projection, selection, selectionArgs, null, null,
169 | sortOrder);
170 | cursor.setNotificationUri(getContext().getContentResolver(), uri);
171 | return cursor;
172 | }
173 | }
174 | throw new IllegalArgumentException("Unknown uri: " + uri);
175 | }
176 |
177 | @Nullable
178 | @Override
179 | public String getType(Uri uri)
180 | {
181 | return null;
182 | }
183 |
184 | @Nullable
185 | @Override
186 | public Uri insert(Uri uri, ContentValues values)
187 | {
188 | int uriType = matcher.match(uri);
189 | long id;
190 |
191 | for (String s :
192 | uriMatcherStrings.keySet())
193 | {
194 | if (uriMatcherStrings.get(s).equals(uriType))
195 | {
196 | id = sqldb.insert(s, null, values);
197 | getContext().getContentResolver().notifyChange(uri, null);
198 | return Uri.parse(s + "/" + id);
199 | }
200 | }
201 | throw new IllegalArgumentException("Unknown URI: " + uri);
202 | }
203 |
204 | @Override
205 | public int delete(Uri uri, String selection, String[] selectionArgs)
206 | {
207 | int uriType = matcher.match(uri);
208 | int rowsDeleted;
209 | String id;
210 |
211 | for (String s :
212 | uriMatcherStrings.keySet())
213 | {
214 | if (uriMatcherStrings.get(s).equals(uriType))
215 | {
216 | if (s.endsWith("_ID"))
217 | {
218 | id = uri.getLastPathSegment();
219 | if (TextUtils.isEmpty(selection))
220 | {
221 | rowsDeleted = sqldb.delete(s.replace("_ID", ""), "_id " + "="
222 | + id, null);
223 | } else
224 | {
225 | rowsDeleted = sqldb.delete(s.replace("_ID", ""), "_id " + "="
226 | + id + " and " + selection, null);
227 | }
228 | } else
229 | {
230 | rowsDeleted = sqldb.delete(s, selection, selectionArgs);
231 | }
232 | getContext().getContentResolver().notifyChange(uri, null);
233 | return rowsDeleted;
234 | }
235 | }
236 | throw new IllegalArgumentException("Unknown uri: " + uri);
237 | }
238 |
239 |
240 | @Override
241 | public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
242 | {
243 | int rowsUpdated;
244 | String id;
245 | int uriType = matcher.match(uri);
246 |
247 |
248 | for (String s :
249 | uriMatcherStrings.keySet())
250 | {
251 | if (uriMatcherStrings.get(s).equals(uriType))
252 | {
253 | if (s.endsWith("_ID"))
254 | {
255 | id = uri.getLastPathSegment();
256 | if (TextUtils.isEmpty(selection))
257 | {
258 | rowsUpdated = sqldb.update(s.replace("_ID", ""), values, "_id" + "=" + id, null);
259 | } else
260 | {
261 | rowsUpdated = sqldb.update(s.replace("_ID", ""), values, "_id" + "=" + id + " and " + selection,
262 | selectionArgs);
263 | }
264 | } else
265 | {
266 | rowsUpdated = sqldb.update(s, values, selection,
267 | selectionArgs);
268 | }
269 | getContext().getContentResolver().notifyChange(uri, null);
270 | return rowsUpdated;
271 | }
272 | }
273 | throw new IllegalArgumentException("Unknown URI: " + uri);
274 | }
275 |
276 | /**
277 | * Ensures the columns to which access has been requested exist in the table
278 | *
279 | * @param projection the requested columns
280 | * @param uriType the type of the uri requested
281 | */
282 | private void checkColumns(String[] projection, int uriType)
283 | {
284 | HashSet requestedColumns;
285 | HashSet availableColumns;
286 |
287 | String[] available = new String[0];
288 | for (String s :
289 | uriMatcherStrings.keySet())
290 | {
291 | if (uriMatcherStrings.get(s).equals(uriType))
292 | {
293 | available = db.table(s.replace("_ID", "")).getAllColumns();
294 | break;
295 | }
296 | }
297 | if (available.length == 0)
298 | {
299 | throw new IllegalArgumentException("Could not match uri type: " + uriType);
300 | }
301 |
302 | if (projection != null)
303 | {
304 | requestedColumns = new HashSet(Arrays.asList(projection));
305 | availableColumns = new HashSet(Arrays.asList(available));
306 | if (!availableColumns.containsAll(requestedColumns))
307 | {
308 | throw new IllegalArgumentException("Unknown columns in projection");
309 | }
310 | }
311 |
312 | }
313 | }
314 |
--------------------------------------------------------------------------------
/simple-db/src/main/java/me/shalvah/simpledb/Table.java:
--------------------------------------------------------------------------------
1 | package me.shalvah.simpledb;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Collections;
5 | import java.util.Iterator;
6 |
7 | /**
8 | * Models a table in the database
9 | */
10 | public class Table
11 | {
12 | /**
13 | * The name of the table
14 | */
15 | private String name;
16 |
17 | /**
18 | * The columns in the table
19 | */
20 | private ArrayList columns;
21 |
22 | /**
23 | * Create a new table and add columns to it
24 | *
25 | * @param tableName Name of the table
26 | * @param cols array of Columns to be created in the table
27 | */
28 | public Table(String tableName, Column... cols)
29 | {
30 | //set table name, initialize columns
31 | this.name = tableName;
32 | columns = new ArrayList();
33 |
34 |
35 | //add all other columns
36 | Collections.addAll(this.columns, cols);
37 | }
38 |
39 | /**
40 | * Generate SQLite CREATE statement for the table.
41 | * Only to be called by its containing database
42 | *
43 | * @return the create statement
44 | */
45 | String create()
46 | {
47 | String colsCreateStmnt = "";
48 | ArrayList foreignKeys = new ArrayList();
49 | for (Iterator iterator = columns.iterator(); iterator.hasNext(); )
50 | {
51 | Column column = iterator.next();
52 | colsCreateStmnt += column.create();
53 | if (column.isForeignKey())
54 | {
55 | foreignKeys.add(column.foreignKeyStatement());
56 | }
57 | if (iterator.hasNext())
58 | {
59 | colsCreateStmnt += ", ";
60 | }
61 | }
62 | String fkStatement = "";
63 |
64 | for (Iterator iterator = foreignKeys.iterator(); iterator.hasNext(); )
65 | {
66 | String stmnt = iterator.next();
67 | fkStatement += stmnt;
68 | if (iterator.hasNext())
69 | {
70 | fkStatement += ", ";
71 | }
72 | }
73 |
74 | if (!fkStatement.equals(""))
75 | {
76 | colsCreateStmnt+=",";
77 | }
78 |
79 | return "CREATE TABLE "
80 | + name + " ("
81 | + colsCreateStmnt + " "
82 | + fkStatement + ");";
83 | }
84 |
85 | /**
86 | * Generate SQLite DROP statement for the table.
87 | * Only to be called by its containing database
88 | *
89 | * @return the drop statement
90 | */
91 | String drop()
92 | {
93 | return "DROP TABLE IF EXISTS " + name + ";";
94 | }
95 |
96 | /**
97 | * Add a new column to the table
98 | *
99 | * @param col The column
100 | * @return the table
101 | */
102 | public Table add(Column col)
103 | {
104 | this.columns.add(col);
105 | for (Column c :
106 | columns)
107 | {
108 | c.belongsTo(this.name);
109 | }
110 | return this;
111 | }
112 |
113 | /**
114 | * Get the name of the table
115 | *
116 | * @return the name of the table
117 | */
118 | public String name()
119 | {
120 | return name;
121 | }
122 |
123 | /**
124 | * Gets the names of all this table's columns
125 | *
126 | * @return array containing the names of the table's columns
127 | */
128 | public String[] getAllColumns()
129 | {
130 | ArrayList names = new ArrayList();
131 | for (Column col :
132 | this.columns)
133 | {
134 | names.add(col.name());
135 | }
136 |
137 | return names.toArray(new String[0]);
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/simple-db/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | SimpleDb
3 |
4 |
--------------------------------------------------------------------------------
/simple-db/src/test/java/me/shalvah/simpledb/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package me.shalvah.simpledb;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest
13 | {
14 | @Test
15 | public void addition_isCorrect() throws Exception
16 | {
17 | assertEquals(4, 2 + 2);
18 | }
19 | }
--------------------------------------------------------------------------------