Documentation for CultureMesh Android¶
Introduction¶
This is the developer documentation for the Android app for CultureMesh. This app remains in development, so this documentation is geared toward developers, not end users.
This documentation and the source code for the app were created by Stanford University’s Code the Change for CultureMesh.
User Interaction Flow¶
The below diagram illustrates roughly how users move through the app and between different activities.
Launch App
|
ApplicationStart
/ | \
/ | \
/ | \
not logged in / | \ no selected network
/ | has \
/ | selected \
/ | network \
OnboardActivity | ExploreBubblesOpenGL
| | |
LoginActivity +---------------------+
| |
ExploreBubblesOpenGL------+
|
TimelineActivity extends DrawerActivity
/ | | |
/ View Users + +-----+------+------------+-------+
/ | | | | | |
/ +--------+ Settings | Find Network Explore |
FloatingActionButton | | | | |
(Create Button) | | | TimelineActivity Logout
/ \ View Post View Event | |
| | | | | |
| | +---------+---+ +---+-------------+ OnboardActivity
| | | | |
| CreateEventActivity Make Reply | AboutActivity
| |
CreatePostActivity Help
|
OnboardActivity
Structure of Code¶
User Interface¶
The screens displayed to users are called activities. Each one has an associated
*Activity.java
file that defines a *Activity
class. For example, the
timeline for a network has an associated TimelineActivity
that
controls it. Each activity may also include fragments
(e.g. ListNetworksFragment
) that define part of an activity
and can be reused across multiple activities. They are also often used for parts
of the activity that sometimes disappear or are exchanged with other fragments.
Each activity and fragment may also have layouts defined in the res
folder
as activity_*.xml
and content_*.xml
.
Adapters¶
In some activities, large scrollable lists need to be displayed. Generating the
displayable list elements (View
s) for all the items is inefficient, so
RecyclerView
s are used, which efficiently handle generating the list using
adapters. These classes (e.g. RVAdapter
) provide the functionality
RecyclerView
needs to dynamically generate each displayed list element.
Data Models¶
Conceptually, the data stored with CultureMesh, including Place
s,
User
s, Network
s, and Event
s are represented
as models. These models are represented in JSON when in transit between the app
and the server and as instances of the appropriate class
(see models
) within the app. The API
class handles
converting between object and JSON formats, often using constructors and getters
within the model’s class (e.g. Post.getPostJSON
).
Places and Locations¶
Place
s and/or Location
s are part of the definition of a
Network
, and they are used by themselves when displaying lists from
which the user can choose parameters to narrow their search for networks.
The difference between a place and a location is not well captured in their
names. A place defines a particular geographic area that is one of three types:
a City
, a Region
, or a Country
. A location
can be any of those three, and includes definitions for one or more places.
For example, a location might refer to San Francisco, in which case it would
store San Francisco, California, United States
.
Places can also store references to parent places, so this distinction may seem unhelpful. However, we use it because the salient difference between a location and a place is that a place is a separate model that stores all the information CultureMesh has on that place (e.g. name, population, etc.). On the other hand, a location only stores the IDs of the places that define it. In practice, this means that places can be thought of as residing in a list of all places CultureMesh knows about, while locations are used to define networks.
Inheritance Structure¶
Location
(IDs only)
/ \
/ \
/ \
/ \
Place (Abstract) DatabaseLocation (Abstract)
(Full Info) (IDs)
/ | \ / \
/ | \ NearLocation FromLocation
City Region Country (Wrappers for DatabaseLocation)
(Specific cases of Place)
The diagram above illustrates the inheritance hierarchy consisting of classes
storing location/place information. The tree rooted at
DatabaseLocation
exists because of the potential to cache data
locally in a database. This would allow for offline access and better
performance when internet connection is poor. However, the database
we experimented with required that the near (or current) location be specified
using a different class than the from (or origin) location so that their
instance fields could have different names and not conflict in the database.
This is why NearLocation
and FromLocation
exist, as they
are otherwise essentially the same. Whenever they can be treated identically,
DatabaseLocation
can be used. DatabaseLocation also stores
functionality that is common to both subclasses.
Networks, Languages, Events, and Posts¶
A Network
is defined in one of two ways:
- Location-based: The network is defined by a
NearLocation
and aFromLocation
. - Language-based: The network is defined by a
NearLocation
and aLanguage
.
When the network is initially received from the server as a JSON, it is parsed
to create a DatabaseNetwork
, which represents the above properties
by their IDs. Then, that DatabaseNetwork is expanded into a Network
,
which includes full Place
and/or Language
objects for
the above properties.
While not stored in the Network object, there are also lists of
Event
s and Post
s associated with each network. These
are fetched separately from the server each time they are needed. Instead of
separate classes for their ID-only representations coming from the server and
the fuller ones used within the app, they are instantiated in stages within the
API
class. First, their JSON representations are parsed to partially
instantiate them. Then, missing parts (e.g. full Network objects) are fetched
from the server and parsed to fully instantiate the objects.
Both Event and Post are subclasses of FeedItem
, which requires them
to have a public instance field containing a list of comments. This allows them
to both be displayed via polymorphism within a feed like
TimelineActivity
. These comments are represented by
PostReply
objects.
Interfaces for Sending Objects¶
To reduce code redundancy, the API
class uses a series of model
methods that can send PUT
and POST
requests (separate model
methods)
with any object so long as that object can generate a JSON representation of
itself for the request using getPutJSON
or getPostJSON
. The presence
of these methods is enforced by the interfaces Postable
and
Putable
, which allows for the model
methods to be polymorphic.
Other¶
A Point
describes a particular spot on the globe in terms of its
latitude and longitude. It is really just a holder for the two values.
A User
object represents any of CultureMesh’s users. It only stores
parts of their public profiles, so methods that work with private information
like passwords or email addresses take those values as parameters.
Connections to CultureMesh’s Servers¶
Networking operations are performed by making calls to methods in the
API
class. Since networking operations suffer from any inherent
latency in the user’s internet connection, they are performed in a separate
thread using Volley.
Generically then, these methods generally take the following arguments:
(RequestQueue, args ... , Response.Listener<responseType>)
RequestQueue
: A queue that holds the asynchronous tasks to execute. A queue is generally created once for each activity and then used for all API calls in that activity.args
: All the arguments the method needs to create the network request. This often includes IDs of resources to fetch.Response.Listener<...>
: A listener whoseonResponse
method is called with the result of the operation. This occurs whether or not the operation completed successfully.responseType
: The type of the object that is returned by the operation. This is generally some kind ofNetworkResponse
object.
API Authentication¶
API Key¶
The API key must be passed as a parameter with key key
in the URL of all
authenticated API endpoints. The key is stored in Credentials
, which
is not stored in version control or published publicly. The API method
API.getCredentials
method is used to access the key from within the
API
class.
User Credentials¶
When the user logs in to the app the first time, their email and password
are used to authenticate a request for a login token using
API.Get.loginWithCred
. This token is stored in the app’s
SharedPreferences
for future authentication. The user’s password is not stored. If the token
expires due to inactivity, the user is directed to login again.
All tokens older than API.TOKEN_REFRESH
milliseconds are refreshed with the next authenticated request (this is handled
automatically by API.Get.loginToken
, which produces the tokens used
by all API methods that access secured endpoints). Tokens are refreshed much
faster than they expire because the difference between the refresh time and the
expiration time is the maximum allowable inactivity period before users have to
sign in again, and we want this to be long enough to avoid too much
inconvenience.
Conveying Network Responses¶
This object simplifies error reporting by storing whether or not the operation
failed using NetworkResponse.fail
. It also stores the results
of successful operations, which are available through
NetworkResponse.getPayload
. It can store messages describing errors
and create ready-to-display error dialogs to communicate those messages to
users using NetworkResponse.showErrorDialog
.
Authentication Failures¶
In the special case of
authentication errors, the NetworkResponse.setAuthFailed
method can
be used to specify that the failure was authentication-related. When the
resulting error dialog is displayed and dismissed, the user is automatically
redirected to the sign-in screen.
Recommended Usage¶
Specify the network operation to be performed in a method in the
API
class. The method should take aRequestQueue
and aResponse.Listener
.Create the request, such as
JsonObjectRequest
, providing the method of the request (e.g.GET
,POST
, etc.), endpoint URL, listener, and error listener.In the listener, specify an
onResponse
method that handles interpreting the response into aNetworkResponse
and passing that to a call to theResponse.Listener
provided as a parameter to the API method.In the error listener, interpret the error and select an appropriate error message. Create a
NetworkResponse
object to communicate the error. If appropriate, useNetworkResponse.setAuthFailed
.Example method:
static void user(RequestQueue queue, long id, final Response.Listener<NetworkResponse<User>> listener) { JsonObjectRequest authReq = new JsonObjectRequest(Request.Method.GET, API_URL_BASE + "user/" + id + "?" + getCredentials(), null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject res) { try { //make User object out of user JSON. User user = new User(res); listener.onResponse(new NetworkResponse<>(false, user)); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { listener.onResponse(new NetworkResponse<User>(true, processNetworkError("API.Get.user", "ErrorListener", error))); } }); queue.add(authReq); }
Note that
API.API_URL_BASE
is a constant in the API class that specifies the base of the API URLs, thatAPI.processNetworkError
returns a reference to a message describing the error, and thatAPI.getCredentials
returns the API key.
In any API methods that rely on another API method, call the used method as usual, but do anything that relies on the used method’s results in the listener you provide to it. In addition, when passing along
NetworkResponse
errors from the used method, you may need to change the type of response when passing it along. Use the constructor that takes another response object, as this discards any payload (which is not needed for errors) and preserves the authentication failure status.When using an API method in Activities or non-API classes, create a
RequestQueue
for the entire activity and pass it to all calls to API methods. In each call, pass along a listener that describes what to do with the response.
Other¶
First Activity¶
When the application starts from scratch (i.e. is not being launched by
restoring a previous state), the ApplicationStart
activity is
loaded. This performs initialization for the app (e.g. Crashlytics).
Then StartActivity
loads, which is the parent activity at
the root of the app. It doesn’t display anything; all it does is
redirect the user to either TimelineActivity
,
OnboardActivity
, or ExploreBubblesOpenGLActivity
based on whether they have logged in and whether they have a selected
network. When tapping the Back
button, the user eventually ends up at
StartActivity
, which then redirects them. This prevents a user from
returning to OnboardActivity
using the Back
button.
Managing Formatted Text¶
In cases where the user can create formatted text using inline markup (i.e.
bold, italics, and hyperlinks), FormatManager
handles the
markup.
Handling Redirections¶
In a few cases, a parent activity needs to launch a child activity while also
directing the child to launch a particular grand-child activity. For example,
when SettingsActivity
launches OnboardActivity
, the user
should be sent back to SettingsActivity at the end. If
ApplicationStart
is instead launching OnboardActivity
,
the user should next be sent on to LoginActivity
. This is handled
by Redirection
.
Code Reference¶
The Android code is documented using Javadoc, which can be viewed in three forms:
- Traditional Javadoc
(includes
Private
methods) - javasphinx Javadoc (excludes
Private
methods) - The comments in the code itself
Specific sections of the javasphinx Javadoc are referenced throughout the
documentation like so: API.Get
.
Javadoc Table of Contents¶
Javadoc¶
org.codethechange.culturemesh¶
-
class
API
¶ This API serves as the interface between the rest of the app and the CultureMesh servers. When another part of the app needs to request information, it calls API methods to obtain it. Similarly, API methods should be used to store, send, and update information. The API then handles requesting it from the CultureMesh servers.
-
static final String
FEED_ITEM_COUNT_SIZE
¶ The number of items (e.g.
org.codethechange.culturemesh.models.Post
s orEvent
s to fetch with each paginated request
-
static final String
LOGIN_TOKEN
¶ Settings identifier for the currently cached login token for the user. May be missing or expired. Expiration is tracked using
API.TOKEN_REFRESH
.
-
static final int
TOKEN_REFRESH
¶ Number of milliseconds to use a login token before refreshing it. Note that this is not how long the token is valid, just how often to refresh it. Refresh time must be shorter than the validity time.
See also:
API.LOGIN_TOKEN
-
static final String
TOKEN_RETRIEVED
¶ Settings identifier for when the current login token was retrieved. Stored as the number of milliseconds since the epoch.
See also:
API.LOGIN_TOKEN
-
static String
genBasicAuth
(String email, String password)¶ Generate from a username/email and password the string to put in the header of a request as the value of the
Authorization
token in order to perform Basic Authentication. For example:headers.put("Authorization", genBasicAuth(email, password))
. A login token can be used if it is passed as theemail
, in which case thepassword
is ignored by the server.Parameters: - email – Email or username of account to login as; can also be a login token
- password – Password to login with
Returns: Value that should be passed in the header as the value of
Authorization
-
static String
genBasicAuth
(String token)¶ Generate from a login token the string to put in the header of a request as the value of the
Authorization
token in order to perform Basic Authentication. For example:headers.put("Authorization", genBasicAuth(token))
.Parameters: - token – Login token to authenticate to server
Returns: Value that should be passed in the header as the value of
Authorization
-
static class
Get
¶ The protocol for GET requests is as follows… 1. Check if cache has relevant data. If so, return it. 2. Send network request to update data.
-
static void
autocompleteLanguage
(RequestQueue queue, String text, Response.Listener<NetworkResponse<List<Language>>> listener)¶ Get potential
Language
s that match a user’s query textParameters: - queue – Queue to which the asynchronous task will be added
- text – User’s query text to get autocomplete results for
- listener – Listener whose
com.android.volley.Response.Listener.onResponse(Object)
is called with theNetworkResponse
created by the query.
-
static void
autocompletePlace
(RequestQueue queue, String text, Response.Listener<NetworkResponse<List<Location>>> listener)¶ Get potential
Location
s that match a user’s query textParameters: - queue – Queue to which the asynchronous task will be added
- text – User’s query text to get autocomplete results for
- listener – Listener whose
com.android.volley.Response.Listener.onResponse(Object)
is called with theNetworkResponse
created by the query.
-
static void
instantiatePostReplyUser
(RequestQueue queue, PostReply comment, Response.Listener<PostReply> listener)¶ The API will return Post JSON Objects with id’s for the user. Often, we will want to get the user information associated with a post, such as the name and profile picture. This method allows us to instantiate this user information for each post.
Parameters: - queue – The Volley RequestQueue object that handles all the request queueing.
- comment – An already instantiated PostReply object that has a null author field but a defined userId field.
- listener – the UI listener that will be called when we complete the task at hand.
-
static void
instantiatePostUser
(RequestQueue queue, org.codethechange.culturemesh.models.Post post, Response.Listener<org.codethechange.culturemesh.models.Post> listener)¶ The API will return Post JSON Objects with id’s for the user. Often, we will want to get the user information associated with a post, such as the name and profile picture. This method allows us to instantiate this user information for each post.
Parameters: - queue – The Volley RequestQueue object that handles all the request queueing.
- post – An already instantiated Post object that has a null author field but a defined userId field.
- listener – the UI listener that will be called when we complete the task at hand.
-
static void
language
(RequestQueue queue, long id, Response.Listener<NetworkResponse<Language>> listener)¶ Get the
Language
that has the provided IDParameters: - queue – Queue to which the asynchronous task will be added
- id – ID of the
Language
to find. Must be unique, and the same ID must be used throughout. - listener – Listener whose
com.android.volley.Response.Listener.onResponse(Object)
is called with theNetworkResponse
created by the query.
Generically get a login token. If the token is fresh (less than
API.TOKEN_REFRESH
seconds have passed since the last token was retrieved the current token is simply supplied. Otherwise, an attempt is made to login with the token to get a new one. If this fails, the token has expired, and the user is directed to sign in again by the error dialog. If it succeeds, the new token is stored in place of the old one.Parameters: - queue – Queue to which the asynchronous task will be added
- listener – Listener whose onResponse method will be called when task completes
See also:
NetworkResponse.genErrorDialog(Context,int,boolean,NetworkResponse.DialogTapListener)
,API.LOGIN_TOKEN
,API.TOKEN_RETRIEVED
Use a user’s login credentials to login to the server. A user’s credentials consist of the email address associated with their account and their password for the CultureMesh website. If the credentials are accepted by the server, the resulting LoginResponse will be stored in the
NetworkResponse
, which will not be in a failed state, and passed to the listener. If the credentials are rejected, theNetworkResponse
will be in a failed state with an error message communicating the occurrence of an authentication failure and instructing the user to sign in again. After dismissing the error dialog, theLoginActivity
will be launched.Parameters: - queue – Queue to which the asynchronous task will be added
- email – Email address that will serve as the username in the attempted login
- password – Password to use in the login attempt
- listener – Will be called with the
NetworkResponse
when the operation completes
See also:
NetworkResponse.genErrorDialog(Context,int,boolean,NetworkResponse.DialogTapListener)
Same as
API.Get.loginWithCred(RequestQueue,String,String,SharedPreferences,Response.Listener)
, but a login token is used in place of the user’s credentials.Parameters: - queue – Queue to which the asynchronous task will be added
- token – Login token to use to get another token
- listener – Will be called with the
NetworkResponse
when the operation completes
-
static void
netFromFromAndNear
(RequestQueue queue, FromLocation from, NearLocation near, Response.Listener<NetworkResponse<Network>> listener)¶ Get the
Network
that has the providedFromLocation
andNearLocation
Parameters: - queue – Queue to which the asynchronous task will be added
- from –
FromLocation
of theNetwork
to find - near –
NearLocation
of theNetwork
to find - listener – Listener whose
com.android.volley.Response.Listener.onResponse(Object)
is called with theNetworkResponse
created by the query.
-
static void
netFromLangAndNear
(RequestQueue queue, Language lang, NearLocation near, Response.Listener<NetworkResponse<Network>> listener)¶ Get the
Network
that has the providedLanguage
andNearLocation
Parameters: - queue – Queue to which the asynchronous task will be added
- lang –
Language
of theNetwork
to find - near –
NearLocation
of theNetwork
to find - listener – Listener whose
com.android.volley.Response.Listener.onResponse(Object)
is called with theNetworkResponse
created by the query.
-
static void
network
(RequestQueue queue, long id, Response.Listener<NetworkResponse<Network>> callback)¶ Get the
Network
corresponding to the provided IDParameters: - queue – Queue to which the asynchronous task to get the
Network
will be added - id – ID of the
Network
to get - callback – Listener whose
com.android.volley.Response.Listener.onResponse(Object)
is called with theNetworkResponse
created by the query.
- queue – Queue to which the asynchronous task to get the
-
static void
networkEvents
(RequestQueue queue, long id, String maxId, Response.Listener<NetworkResponse<List<Event>>> listener)¶ Get the
Event
s corresponding to aNetwork
Parameters: - queue – Queue to which the asynchronous task will be added
- id – ID of the
Network
whoseEvent
s will be fetched - listener – Listener whose
com.android.volley.Response.Listener.onResponse(Object)
is called with theNetworkResponse
created by the query.
-
static void
networkPostCount
(RequestQueue queue, long id, Response.Listener<NetworkResponse<Long>> listener)¶ Get the number of
org.codethechange.culturemesh.models.Post
s that are currently on aNetwork
Parameters: - queue – Queue to which the asynchronous task will be added
- id – ID of the
Network
whoseorg.codethechange.culturemesh.models.Post
count will be retrieved - listener – Listener whose
Response.Listener.onResponse(Object)
is called with aNetworkResponse
that stores the result of the network request
-
static void
networkPosts
(RequestQueue queue, long id, String maxId, Response.Listener<NetworkResponse<List<org.codethechange.culturemesh.models.Post>>> listener)¶ Get the
org.codethechange.culturemesh.models.Post
s of aNetwork
Parameters: - queue – Queue to which the asynchronous task will be added
- id – ID of the
Network
whoseorg.codethechange.culturemesh.models.Post
s will be returned - listener – Listener whose
com.android.volley.Response.Listener.onResponse(Object)
is called with theNetworkResponse
created by the query.
-
static void
networkUserCount
(RequestQueue queue, long id, Response.Listener<NetworkResponse<Long>> listener)¶ Get the number of
User
s who are currently members of aNetwork
Parameters: - queue – Queue to which the asynchronous task will be added
- id – ID of the
Network
whoseUser
count will be retrieved - listener – Listener whose
Response.Listener.onResponse(Object)
is called with aNetworkResponse
that stores the result of the network request
-
static void
networkUsers
(RequestQueue queue, long id, Response.Listener<NetworkResponse<ArrayList<User>>> listener)¶ Get all the
User
s who are members of aNetwork
Parameters: - queue – Queue to which the asynchronous task will be added
- id – ID of the
Network
whose users will be fetched - listener – Listener whose
com.android.volley.Response.Listener.onResponse(Object)
is called with theNetworkResponse
created by the query.
-
static void
post
(RequestQueue queue, long id, Response.Listener<NetworkResponse<org.codethechange.culturemesh.models.Post>> callback)¶ Get a
org.codethechange.culturemesh.models.Post
from it’s IDParameters: - queue – Queue to which the asynchronous task will be added
- id – ID of the
org.codethechange.culturemesh.models.Post
to retrieve - callback – Listener whose
com.android.volley.Response.Listener.onResponse(Object)
is called with theNetworkResponse
created by the query.
-
static void
postReplies
(RequestQueue queue, long id, Response.Listener<NetworkResponse<ArrayList<PostReply>>> listener)¶ Fetch the comments of a post.
Parameters: - queue – The
RequestQueue
to house the network requests. - id – the id of the post that we want comments for.
- listener – the listener that we will call when the request is finished.
- queue – The
-
static void
topTen
(RequestQueue queue, Response.Listener<NetworkResponse<ArrayList<Network>>> listener)¶ Fetches the ten
Network
s with the most subscribers.Parameters: - queue – Queue to which the asynchronous task will be added
- listener – Will be called with the
NetworkResponse
when the operation completes
-
static void
user
(RequestQueue queue, long id, Response.Listener<NetworkResponse<User>> listener)¶ Get a
User
object from it’s IDParameters: - id – ID of user to find
Returns: If such a user was found, it will be the payload. Otherwise, the request will be marked as failed.
-
static void
userEvents
(RequestQueue queue, long id, String role, Response.Listener<NetworkResponse<ArrayList<org.codethechange.culturemesh.models.Event>>> listener)¶ Get the
Event
s aUser
is subscribed to.Parameters: - queue – Queue to which the asynchronous task is added.
- id – ID of the
User
whose events are being searched for - role – Either
hosting
orattending
- listener – Listener whose
onResponse
method is called with the results of the task
Get the
Event
s aUser
is subscribed to for a givenNetwork
.Parameters: - queue – Queue to which the asynchronous task is added.
- settings – SharedPreferences instance storing the token.
- networkId – the id of the
Network
of interest. - listener – The response listener to be called when the request completes.
-
static void
userID
(RequestQueue queue, String email, Response.Listener<NetworkResponse<Long>> listener)¶ Get the ID of a
User
from an email address. Errors are communicated via a failedNetworkResponse
.Parameters: - queue – Queue to which the asynchronous task will be added
- email – Email of user whose ID to look up
- listener – Listener whose onResponse method is called when the task has completed
-
static void
userNetworks
(RequestQueue queue, long id, Response.Listener<NetworkResponse<ArrayList<Network>>> listener)¶ Get the networks a user belongs to
Parameters: - queue – RequestQueue to which the asynchronous job will be added
- id – ID of the user whose networks will be fetched
- listener – Listener whose
com.android.volley.Response.Listener.onResponse(Object)
is called with aNetworkResponse
of anArrayList
ofNetwork
s
-
static void
userPosts
(RequestQueue queue, long id, Response.Listener<NetworkResponse<ArrayList<org.codethechange.culturemesh.models.Post>>> listener)¶ Get the
org.codethechange.culturemesh.models.Post
s aUser
has made.Parameters: - queue – The
RequestQueue
that will house the network requests. - id – The id of the
User
. - listener – The listener that the UI will call when the request is finished.
- queue – The
-
static class
Post
¶
POST to the server a request, via
/event/new
, to create a newEvent
. Success or failure status will be passed via aNetworkResponse
to the listener.Parameters: - queue – Queue to which the asynchronous task will be added
- event –
Event
to create. - listener – Listener whose onResponse method will be called when task completes
Add a user to an existing event. This operation requires authentication, so the user must be logged in.
Parameters: - queue – Queue to which the asynchronous task will be added
- settings –
SharedPreferences
instance so we can get the token. - eventId – ID of the event to add the user to
- listener – Listener whose onResponse method will be called when the operation completes
Add the current user to an existing network. This operation requires authentication, so the user must be logged in.
Parameters: - queue – Queue to which the asynchronous task will be added
- networkId – ID of the network to add the user to
- listener – Listener whose onResponse method will be called when the operation completes
Removes user from event subscription listing.
Parameters: - queue – Queue to which network request will be added.
- eventId – id of event to remove user from.
- settings –
SharedPreferences
instance that stores token. - listener – Listener whose onResponse will be called when the operation completes.
Remove the current user from a network. This operation requires authentication, so the user must be logged in. If the user is not in the specified network, no error is thrown.
Parameters: - queue – Asynchronous task to which the request will be added
- networkId – ID of the network to remove the user from
- settings – Reference to the
SharedPreferences
storing the user’s login token - listener – Listener whose
onResponse
method will be called when the operation completes
POST to the server a request, via
/post/new
, to create a neworg.codethechange.culturemesh.models.Post
. Success or failure status will be passed via aNetworkResponse
to the listener.Parameters: - queue – Queue to which the asynchronous task will be added
- post –
org.codethechange.culturemesh.models.Post
to create. - listener – Listener whose onResponse method will be called when task completes
POST to the server a request, via
/post/{postId}/reply
, to create a newPostReply
. Success or failure status will be passed via aNetworkResponse
to the listener.Parameters: - queue – Queue to which the asynchronous task will be added
- comment –
PostReply
to create. - listener – Listener whose onResponse method will be called when task completes
-
static void
user
(RequestQueue queue, User user, String email, String password, Response.Listener<NetworkResponse<String>> listener)¶ POST to the server a request, via
/user/users
, to create a new user. Note that Success or failure status will be passed via aNetworkResponse
to the listener.Parameters: - queue – Queue to which the asynchronous task will be added
- user – User to create. Must have password set.
- email – User’s email address
- listener – Listener whose onResponse method will be called when task completes
-
static class
Put
¶
PUT to the server a request, via
/event/new
, to update anEvent
. Success or failure status will be passed via aNetworkResponse
to the listener.Parameters: - queue – Queue to which the asynchronous task will be added
- event – Updated version of the
Event
to change - listener – Listener whose onResponse method will be called when task completes
PUT to the server, via
/user/users
, a request to make changes aorg.codethechange.culturemesh.models.Post
. Success or failure status will be passed via aNetworkResponse
to the listener.Parameters: - queue – Queue to which the asynchronous task will be added
- post – Updated version of the post to change
- listener – Listener whose onResponse method will be called when task completes
PUT to the server a request, via
/post/{postId}/reply
, to update aPostReply
. Success or failure status will be passed via aNetworkResponse
to the listener.Parameters: - queue – Queue to which the asynchronous task will be added
- comment – Updated version of the
PostReply
to make changes to - listener – Listener whose onResponse method will be called when task completes
PUT to the server, via
/user/users
, a request to make changes aUser
. Success or failure status will be passed via aNetworkResponse
to the listener.Parameters: - queue – Queue to which the asynchronous task will be added
- user – Updated version of the user to change
- email – User’s email address
- listener – Listener whose onResponse method will be called when task completes
-
public class
AboutActivity
extends DrawerActivity¶ Activity for displaying author attributions, copyright notices, and version information on an
About
page
-
protected void
onCreate
(Bundle savedInstanceState)¶ When the activity is created, it pulls what to display from
R.layout.activity_about
. It does not have asetSupportActionBar(toolbar)
call because that is handled byDrawerActivity
. The toolbar MUST have an ID ofaction_bar
.Parameters: - savedInstanceState – Passed to superclass onCreate method
-
public void
openLegal
(View v)¶ Open
Acknowledgements
activity to display legally required attributions for the open-source libraries we useParameters: - v – The
View
of the button clicked on to run this method. Not used.
- v – The
-
public class
Acknowledgements
extends DrawerActivity¶ A
DrawerActivity
that displays legally required attributions for the open-source code we use.
-
protected void
onCreate
(Bundle savedInstanceState)¶ Link the activity to its layout specified in
R.layout.activity_acknowledgements
Parameters: - savedInstanceState – {@inheritDoc}
-
public class
AnimationUtils
¶ This is a utility class to show the loading overlay for activities that require network requests to display their data.
-
public static void
animateLoadingOverlay
(View view, int toVisibility, float toAlpha, int duration)¶ Shows or hides loading overlay with smooth alpha transition. Sourced from https://stackoverflow.com/questions/18021148/display-a-loading-overlay-on-android-screen
Parameters: - view – View to animate
- toVisibility – Visibility at the end of animation
- toAlpha – Alpha at the end of animation
- duration – Animation duration in ms
-
public class
ApplicationStart
extends Application¶ This serves as a landing page for when the app is started from scratch. It does some initialization.
-
public class
ChooseNearLocationActivity
extends AppCompatActivity implements SearchView.OnQueryTextListener¶ This screen let’s the user choose where they live now. This is used by
FindNetworkActivity
to restrict displayed networks to those with anear
that matches where the user lives.
-
protected void
onCreate
(Bundle savedInstanceState)¶ Setup the activity. Also initializes the
com.android.volley.RequestQueue
, the adapter that populates the list of results, and the listener that handles clicks on items in the results listParameters: - savedInstanceState – Previous state that is passed through to superclass
-
public boolean
onQueryTextSubmit
(String query)¶ When the user submits their query,
ChooseNearLocationActivity.search()
is run to populated the results with matchingLocation
sParameters: - query – User’s query. Not used.
Returns: Always returns
true
-
public void
search
()¶ Get the query present in the
ChooseNearLocationActivity.searchView
and pass it to the server viaAPI.Get.autocompletePlace(RequestQueue,String,Response.Listener)
to get a list of matchingLocation
s. These are used to populate theChooseNearLocationActivity.adapter
.
-
SharedPreferences
settings
¶ The app’s shared settings that store user info and preferences
-
public void
onAttach
(Context context)¶ -
Parameters: - context – {@inheritDoc}
-
public void
onCreate
(Bundle savedInstanceState)¶ Initialize references to
CommentsFrag.queue
andCommentsFrag.settings
.Parameters: - savedInstanceState –
-
public View
onCreateView
(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)¶ Populate the activity with UI elements
Parameters: - inflater – Inflates the xml
R.layout.fragment_comments
into the displayed UI - container – TODO: What is this?
- savedInstanceState – Saved state that can be restored. Not used.
Returns: The inflated view produced by
inflater
- inflater – Inflates the xml
-
public class
CreateEventActivity
extends AppCompatActivity¶ Screen through which users can create an event in their currently selected network
-
public static class
DatePickerFragment
extends DialogFragment implements DatePickerDialog.OnDateSetListener¶ DatePicker static class that handles operations of the time selection fragment
-
public DatePicker
getDatePicker
()¶ Get the DatePicker
Returns: The DatePicker
-
public int
getDay
()¶ Get the selected day
Returns: The selected day of the month with the first day represented by 1
-
public int
getMonth
()¶ Get the selected month
Returns: The selected month as an integer with January as 0 and December as 11
-
public int
getYear
()¶ Get the selected year
Returns: The selected year (e.g. 2004 returns the integer 2004)
-
public boolean
isSet
()¶ Check whether the user has set a date
Returns: true if the user has set a date, false otherwise
-
public Dialog
onCreateDialog
(Bundle savedInstanceState)¶ Called when the fragment is created Sets the initial state of the calendar to the current date and returns the resulting DatePickerDialog to display
Parameters: - savedInstanceState – Last saved state of fragment
Returns: DatePickerDialog to display to the user
-
public void
onDateSet
(DatePicker view, int year, int month, int day)¶ When user sets the date, show their choice in the eventDate textView
Parameters: - view – The date picker shown via the fragment
- year – Year the user chose
- month – Month the user chose
- day – Day the user chose
-
public static class
TimePickerFragment
extends DialogFragment implements TimePickerDialog.OnTimeSetListener¶ TimePicker static class that handles operations of the time selection fragment
-
public TimePicker
getTimePicker
()¶ Return the TimePicker
Returns: the TimePicker
-
public boolean
isSet
()¶ Check whether the user has set a time yet
Returns: true if the user has set the time, false otherwise
-
public Dialog
onCreateDialog
(Bundle savedInstanceState)¶ Called when the fragment is created Sets the initial state of the clock to the current time and returns the resulting TimePickerDialog to display
Parameters: - savedInstanceState – Last saved state of fragment
Returns: TimePickerDialog to display
-
public void
onTimeSet
(TimePicker view, int inHour, int inMin)¶ When user sets the time, show their choice in the eventTime textView
Parameters: - view – The time picker shown via the fragment
- inHour – Hour the user set
- inMin – Minute the user set
-
public class
CreatePostActivity
extends AppCompatActivity implements FormatManager.IconUpdateListener¶ Creates screen the user can use to create a new
Post
-
ListenableEditText
content
¶ Field the user uses to type the body of their
Post
-
FormatManager
formatManager
¶ Handles markup of the body text
-
ProgressBar
progressBar
¶ Displays progress as the post is being sent over the network
-
protected void
onCreate
(Bundle savedInstanceState)¶ Create the screen from
R.layout.activity_create_post
, fillCreatePostActivity.networkLabel
with a description of theNetwork
fromAPI.Get.network(RequestQueue,long,Response.Listener)
, setupCreatePostActivity.formatManager
, and link a listener to the submission button that sends thePost
usingAPI.Post.post(RequestQueue,Post,SharedPreferences,Response.Listener)
Parameters: - savedInstanceState – {@inheritDoc}
-
public boolean
onOptionsItemSelected
(MenuItem item)¶ This function handles what happens when our format toggle buttons are clicked. We want to update the content formatting when this happens as well with Spannables. Check out https://stackoverflow.com/questions/10828182/spannablestringbuilder-to-create-string-with-multiple-fonts-text-sizes-etc-examp for more info.
Parameters: - item – the MenuItem that was tapped.
-
public void
onStop
()¶ This ensures that we are canceling all network requests if the user is leaving this activity. We use a RequestFilter that accepts all requests (meaning it cancels all requests)
-
public void
updateIconToggles
(SparseBooleanArray formTogState, SparseArray<int[]> toggleIcons)¶ This fancy function uses our SparseArray’s to concisely iterate over our toggle icons and update their colors - white if untoggled, black if toggled.
-
public class
Credentials
¶ Just a file out of source control that you can use to hide our API Key. In reality, we won’t be using a static API Key (in theory, someone could reverse engineer this somehow), but we’ll be using it for beta testing. Thus, make sure you don’t add it to source control (Git) and push it onto the master branch.
-
public class
DrawerActivity
extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener¶ Superclass for all Activities that have a navigation drawer
-
protected FrameLayout
frameLayout
¶ Parent for the drawer activity
-
protected DrawerLayout
fullLayout
¶ The inflated user interface for the activity with the drawer
-
protected DrawerLayout
mDrawerLayout
¶ User interface for the drawer itself
-
protected ActionBarDrawerToggle
mDrawerToggle
¶ Toggles whether the drawer is visible
-
public void
fetchNetworks
()¶ This fetches the users subscribed networks and displays them in the navigation drawer.
-
public void
onConfigurationChanged
(Configuration newConfig)¶ {@inheritDoc} Also updates the configuration of the drawer toggle by calling
DrawerActivity.mDrawerToggle.onConfigurationChanged(Configuration)
with the provided parameter.Parameters: - newConfig – {@inheritDoc}
-
protected void
onPostCreate
(Bundle savedInstanceState)¶ {@inheritDoc} Also syncs the state of
DrawerActivity.mDrawerToggle
Parameters: - savedInstanceState – {@inheritDoc}
-
public class
ExploreBubblesOpenGLActivity
extends DrawerActivity¶ Display moving bubbles which show suggested networks for the user to join
-
public class
FindNetworkActivity
extends DrawerActivity¶
-
protected void
onActivityResult
(int requestCode, int resultCode, Intent data)¶ When the user has chosen a near location using
ChooseNearLocationActivity
, this method is called by theIntent
that launched the near location chooser with the result of the user’s selection. If they did indeed choose a location, that location is saved and the button text is updated to reflect the location’s name.Parameters: - requestCode – Status code that indicates a location was chosen if it equals
ChooseNearLocationActivity.RESULT_OK
- resultCode – {@inheritDoc}
- data – Passed to superclass, but the value associated with
ChooseNearLocationActivity.CHOSEN_PLACE
, which should be the location the user chose, is extracted ifrequestCode
indicates they made a choice
- requestCode – Status code that indicates a location was chosen if it equals
-
public boolean
onOptionsItemSelected
(MenuItem item)¶ Handles clicks to the action bar.
Parameters: - item – {@inheritDoc}
Returns: true
if the item ID is that ofR.id.action_settings
. Otherwise, superclassonOptionsItemSelected
is called and the resulting value is returned.
-
public static class
FindLanguageFragment
extends Fragment implements SearchView.OnQueryTextListener¶ The fragment for finding language networks.
-
public static FindLanguageFragment
newInstance
(int sectionNumber)¶ Returns a new instance of this fragment for the given section number.
-
public View
onCreateView
(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)¶ Create the displayed fragment.
Parameters: - inflater – Creates the user interface from
R.layout.fragment_find_language
- container – Parent container to attach inflated
View
to - savedInstanceState – Previous state that is not used.
Returns: The inflated view to display.
- inflater – Creates the user interface from
-
public boolean
onQueryTextSubmit
(String query)¶ When the user submits a query, call
FindLanguageFragment.search()
Parameters: - query – Query text that is discarded.
Returns: Always returns
true
-
public void
search
()¶ Use
API.Get.autocompleteLanguage(RequestQueue,String,Response.Listener)
to get autocomplete results for the user’s query. Pass those results toFindLanguageFragment.adapter
, which will then populateFindLanguageFragment.searchList
-
public static class
FindLocationFragment
extends Fragment implements SearchView.OnQueryTextListener¶ The fragment for finding the from location.
-
public static FindLocationFragment
newInstance
(int sectionNumber)¶ Returns a new instance of this fragment for the given section number.
-
public View
onCreateView
(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)¶ Create the displayed fragment.
Parameters: - inflater – Creates the user interface from
R.layout.fragment_find_location
- container – Parent container to attach inflated
View
to - savedInstanceState – Previous state that is not used.
Returns: The inflated view to display.
- inflater – Creates the user interface from
-
public boolean
onQueryTextSubmit
(String query)¶ When the user submits a query, call
FindLocationFragment.search()
Parameters: - query – Query text that is discarded.
Returns: Always returns
true
-
public void
search
()¶ Use
API.Get.autocompletePlace(RequestQueue,String,Response.Listener)
to get autocomplete results for the user’s query. Pass those results toFindLocationFragment.adapter
, which will then populateFindLocationFragment.searchList
-
public class
SectionsPagerAdapter
extends FragmentPagerAdapter¶ A
FragmentPagerAdapter
that returns a fragment corresponding to one of the two available tabs:From
, for location-based networks, andSpeaks
, for language-based networks.
-
SectionsPagerAdapter
(FragmentManager fm)¶ -
Parameters: - fm – {@inheritDoc}
-
public Fragment
getItem
(int position)¶ Get the appropriate fragment depending on which tab is selected
Parameters: - position – Either
0
, fornear
or1
, forspeaks
Returns: FindLocationFragment
forposition=1
,FindLanguageFragment
otherwise.- position – Either
-
public CharSequence
getPageTitle
(int position)¶ Get the titles for each tab
Parameters: - position – Position of tab to get name of (
0
or1
)
Returns: Reference to name of tab
- position – Position of tab to get name of (
-
public class
FormatManager
implements ListenableEditText.onSelectionChangedListener¶ Created by Drew Gregory on 3/26/18. This class provides a little decomposition from CreatePost/SpeciticPostActivity in that it handles all the formatting involved in writing posts/post replies. The supported formatting is: - bold - italic - links This formatting is embedded in the SpannableStrings that EditTexts can produce and maintain. This manager will also handle the tedious tasks of updating the toggle icons and maintaining state. When the user is done formatting and wants to publish their post/post reply, call the toString(), which will convert the spannable to a string with the proper tags as specified by Ian Nottage: Bold text Italic text Link text
-
FormatManager
(ListenableEditText content, IconUpdateListener listener, int boldIcon, int italicIcon, int linkIcon)¶
-
public static String
abbreviateNumber
(long number)¶ In the interest of screen space and accessibility, we will format the number to have a magnitude suffix instead of the exact number.
Parameters: - number – exact number, in floating point if necessary.
Returns: Formatted String representing number magnitude (e.x. 100K)
-
public static Spanned
fromHtml
(String html)¶ Different Android versions use different fromHtml method signatures. Sourced from https://stackoverflow.com/questions/37904739/html-fromhtml-deprecated-in-android-n
Parameters: - html –
-
public static Spanned
parseText
(String formattedText, String colorString)¶ This function converts the CultureMesh tags into a spannable string for textview.
Parameters: - formattedText – should only have
<b></b>, <link></link>, <i></i> or [b][/b][link][/link][i][/i]
- colorString – the link color in RGB. Some text has different color backgrounds.
Returns: Spannable to be passed to TextView.
- formattedText – should only have
-
public interface
IconUpdateListener
¶
-
void
updateIconToggles
(SparseBooleanArray formTogState, SparseArray<int[]> toggleIcons)¶ This method will require the parent activity to update the toggle button icons.
Parameters: - formTogState – a SparseBooleanArray (HashMap) with int as key and boolean as value key: int id of toggleButton View we are using. value: true if toggled, false if not toggled.
- toggleIcons – a SparseArray (HashMap) with int as key and int[] as value. key: int id of toggleButton View we are using. value: int[0] being untoggled icon, int[1] being toggled icon.
-
public class
HelpActivity
extends OnboardActivity¶ Show user onboarding screens again as help
-
public class
ListNetworksFragment
extends Fragment implements NetworkSummaryAdapter.OnNetworkTapListener¶ Fragment for displaying lists of clickable networks
-
public static ListNetworksFragment
newInstance
(long selUser)¶ Returns a new instance of this fragment for the given section number.
-
public View
onCreateView
(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)¶ Setup the user interface to display the list of networks and populate that list with the result of calling
API.Get.userNetworks(RequestQueue,long,Response.Listener)
.Parameters: - inflater – Inflates the user interface specified in
R.layout.rv_container
- container – Parent of the generated hierarchy of user interface elements
- savedInstanceState – Saved state to restore
Returns: Inflated user interface
- inflater – Inflates the user interface specified in
-
public class
ListUserEventsFragment
extends Fragment implements RVAdapter.OnItemClickListener¶ This fragment lists the the events a user is subscribed to. It is used in ViewProfileActivity.
-
public static ListUserEventsFragment
newInstance
(long selUser)¶ Returns a new instance of this fragment for the given section number.
-
public View
onCreateView
(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)¶ Setup the user interface to display the list of events and populate that list with the result of calling
API.Get.userEvents(RequestQueue,long,String,Response.Listener)
.Parameters: - inflater – Inflates the user interface specified in
R.layout.rv_container
- container – Parent of the generated hierarchy of user interface elements
- savedInstanceState – Saved state to restore
Returns: Inflated user interface
- inflater – Inflates the user interface specified in
-
public class
ListUserPostsFragment
extends Fragment implements RVAdapter.OnItemClickListener¶ Creates screen that displays the
Post
s aorg.codethechange.culturemesh.models.User
has made.
-
RecyclerView
rv
¶ Scrollable list of
Post
s
-
public static ListUserPostsFragment
newInstance
(long selUser)¶ Returns a new instance of this fragment for the given section number.
-
public View
onCreateView
(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)¶ Create the user interface. Also populate the list of
Post
s with the result fromAPI.Get.userPosts(RequestQueue,long,Response.Listener)
Parameters: - inflater – Inflates the user interface from
R.layout.rv_container
with the providedcontainer
as the parent. - container – Parent used by
inflater
- savedInstanceState – Not used
Returns: The inflated user interface
- inflater – Inflates the user interface from
-
public void
onItemClick
(FeedItem item)¶ When the user clicks on an item, redirect them to
SpecificPostActivity
where more details, including comments, are displayed.Parameters: - item – The clicked item.
-
public interface
Listable
¶ Interface for objects that need to be listed in the user interface.
-
String
getListableName
()¶ Get a label (maximum of
Listable.MAX_CHARS
characters long) to display as an identifier for the object.Returns: Displayable name for the object, which must be less than or equal to Listable.MAX_CHARS
characters long
-
public class
ListenableEditText
extends EditText¶ This is a custom EditText that allows us to listen for changes in cursor position.
CreatePostActivity
uses this view so that the format toggle buttons can update their settings when a new near_region in the edit text is selected.
-
onSelectionChangedListener
mListener
¶
-
public
ListenableEditText
(Context context)¶ -
Parameters: - context – {@inheritDoc}
-
public
ListenableEditText
(Context context, AttributeSet attrs)¶ -
Parameters: - context – {@inheritDoc}
- attrs – {@inheritDoc}
-
public
ListenableEditText
(Context context, AttributeSet attrs, int defStyleAttr)¶ -
Parameters: - context – {@inheritDoc}
- attrs – {@inheritDoc}
- defStyleAttr – {@inheritDoc}
-
protected void
onSelectionChanged
(int selStart, int selEnd)¶ When the selection changes, if it is due to the user typing a character,
ListenableEditText.mListener.onSelectionChanged(int,int)
is called with the provided parameters. Otherwise, the superclass methodEditText.onSelectionChanged(int,int)
is called with the parameters.Parameters: - selStart – TODO: What is this?
- selEnd – TODO: What is this?
-
public void
setOnSelectionChangedListener
(onSelectionChangedListener listener)¶ Set the listener to the provided parameter
Parameters: - listener – Listener to use when text selection changes
-
public interface
onSelectionChangedListener
¶ Interface that all listeners for
ListenableEditText.mListener
must satisfy.
-
public class
LoginActivity
extends RedirectableAppCompatActivity¶ Login screen that lets a user either sign in with email and password or create a new account
Check whether any user is currently signed in
Parameters: - settings – The app’s shared settings, which store user preferences
Returns: true
if a user is signed in,false
otherwise
-
protected void
onCreate
(Bundle savedInstanceState)¶ Create the user interface from
R.layout.activity_login
. Also setup buttons to perform the associated actions, including log-ins withAPI.Get.loginWithCred(RequestQueue,String,String,SharedPreferences,Response.Listener)
and account creation withAPI.Post.user(RequestQueue,User,String,String,Response.Listener)
. Also sets up the animations to convert between signing in and creating an account.Parameters: - savedInstanceState – {@inheritDoc}
Largely for testing, this public method can be used to set which user is currently logged in This is useful for PickOnboardingStatusActivity because different login states correspond to different users. No logged-in user is signalled by a missing SharedPreferences entry.
Parameters: - settings – The SharedPreferences storing user login state
- userID – ID of the user to make logged-in
Logout the currently logged-out user. If no user is logged in, nothing happens
Parameters: - settings – The app’s shared settings, which store user preferences
-
public class
NetworkResponse
<E>¶ Class to store responses after attempting networking tasks
-
public
NetworkResponse
(NetworkResponse<?> toConvert)¶ Create a new NetworkResponse of the type designated in
<>
from another NetworkResponse of any other type. Any payload in the source object will not be transferred to the created one. All other fields are copied.Parameters: - toConvert – Source to create new object from. All properties except payload will be copied.
-
public
NetworkResponse
(boolean inFail)¶ Constructor that creates a generic message based on “inFail”
Parameters: - inFail – Failure state provided by user (true if failed)
-
public
NetworkResponse
(boolean inFail, int inMessageID)¶ Constructor that sets message and failures state based on arguments
Parameters: - inFail – Failure state provided by user (true if failed)
- inMessageID – ID for string resource containing message
-
public
NetworkResponse
(E inPayload)¶ Constructor that stores a payload and sets the failure state to false
Parameters: - inPayload – Payload returned by networking request
-
public boolean
fail
()¶ Check whether the network request failed
Returns: true if the request failed, false if it succeeded
-
public static AlertDialog
genErrorDialog
(Context context, int messageID)¶ Get an error dialog that can be displayed to the user
Parameters: - context – Context upon which to display error dialog (Should be
someClass.this
) - messageID – String resource ID of message to display
Returns: AlertDialog
with specified alert message.- context – Context upon which to display error dialog (Should be
-
public static AlertDialog
genErrorDialog
(Context context, int messageID, DialogTapListener listener)¶ Get an error dialog that can be displayed to the user
Parameters: - context – Context upon which to display error dialog (Should be
someClass.this
) - messageID – String resource ID of message to display
- listener – A
DialogTapListener
for when the user dismisses the dialog.
Returns: AlertDialog
with specified alert message.- context – Context upon which to display error dialog (Should be
-
public static AlertDialog
genErrorDialog
(Context context, int messageID, boolean authFail, DialogTapListener mListener)¶ Get an error dialog that can be displayed to the user
Parameters: - context – Context upon which to display error dialog (Should be
someClass.this
) - messageID – String resource ID of message to display
- authFail – Whether or not the user should be directed to
LoginActivity
upon dismissing the dialog - mListener – A
DialogTapListener
for when the user dismisses the dialog.
Returns: AlertDialog
with specified alert message and which directs the user toLoginActivity
upon dismissal ifauthFail
is true.- context – Context upon which to display error dialog (Should be
-
public static AlertDialog
genSuccessDialog
(Context context, int messageID)¶ Get a confirmation dialog that can be displayed to the user to reflect a successful operation
Parameters: - context – Context upon which to display dialog (Should be
someClass.this
) - messageID – String resource ID of message to display
Returns: AlertDialog
with specified alert message- context – Context upon which to display dialog (Should be
-
public static NetworkResponse<API.Get.LoginResponse>
getAuthFailed
(int messageID)¶ Get a NetworkResponse object with
NetworkResponse.isAuthFailed
istrue
. This means that when the user dismisses the error dialog generated byNetworkResponse.getErrorDialog(Context,DialogTapListener)
orNetworkResponse.showErrorDialog(Context)
,LoginActivity
will be launched.Parameters: - messageID – String reference to the message describing the error. Will be shown to user
Returns: NetworkResponse object to describe an authentication failure.
-
public AlertDialog
getErrorDialog
(Context context, DialogTapListener listener)¶ Get an error dialog that can be displayed to show message from messageID to user
Parameters: - context – Context upon which to display error dialog (Should be
someClass.this
) - listener – A
DialogTapListener
to be called when they dismiss the dialog.
Returns: Dialog that can be shown
- context – Context upon which to display error dialog (Should be
-
public int
getMessageID
()¶ Get the resource ID of the message to display to the user
Returns: Resource ID of message
-
public E
getPayload
()¶ Get the payload returned by the network operation
Returns: Payload returned by network operation
-
public boolean
isAuthFailed
()¶ Get whether the current object represents a failed authentication
Returns: true
if object represents an authentication failure,false
otherwise
-
public void
setAuthFailed
(boolean isAuthFailed)¶ Set whether the current object represents a failed authentication
Parameters: - isAuthFailed –
true
if object represents an authentication failure,false
otherwise
- isAuthFailed –
-
public void
showErrorDialog
(Context context, DialogTapListener listener)¶ Show an error dialog that can be displayed to show message from messageID to user
Parameters: - context – Context upon which to display error dialog
- listener – A
DialogTapListener
object which allows you control behavior after they dismiss the dialog.
-
public class
NetworkSummaryAdapter
extends RecyclerView.Adapter<NetworkSummaryAdapter.PostViewHolder>¶ This functions as the recyclerview adapter for the listview in ViewProfileActivity, where the user can view other users’ subscribed networks.
-
NetworkSummaryAdapter
(ArrayList<Network> networks, HashMap<String, Integer> postCounts, HashMap<String, Integer> userCounts, OnNetworkTapListener listener)¶ Initialize instance fields with parameters
Parameters: - networks – List of
Network
s to display - postCounts – Mapping from the ID of each
Network
to the number oforg.codethechange.culturemesh.models.Post
s it contains - userCounts – Mapping from the ID of each
Network
to the number oforg.codethechange.culturemesh.models.User
s it contains - listener – Listener to handle clicks on list items
- networks – List of
-
public HashMap<String, Integer>
getPostCounts
()¶ Get the mappings between
Network.id
(as aString
) and the number oforg.codethechange.culturemesh.models.Post
s in that network.Returns: Mappings that relate Network
ID to the number oforg.codethechange.culturemesh.models.Post
s in the network
-
public HashMap<String, Integer>
getUserCounts
()¶ Get the mappings between
Network.id
(as aString
) and the number oforg.codethechange.culturemesh.models.User
s in that network.Returns: Mappings that relate Network
ID to the number oforg.codethechange.culturemesh.models.User
s in the network
-
public void
onBindViewHolder
(PostViewHolder holder, int position)¶ Fill the fields of
holder
with the information stored in theNetwork
at indexposition
inNetworkSummaryAdapter.networks
Parameters: - holder – ViewHolder whose fields to fill in
- position – Index of
Network
inNetworkSummaryAdapter.networks
whose information will be used to fill in the fields ofholder
-
public PostViewHolder
onCreateViewHolder
(ViewGroup parent, int viewType)¶ Create a new
NetworkSummaryAdapter.PostViewHolder
from theView
created by inflatingR.layout.network_summary
Parameters: - parent – Parent for created
View
used to create the newNetworkSummaryAdapter.PostViewHolder
- viewType – Not used
Returns: ViewHolder that has been created using an inflated
View
- parent – Parent for created
-
interface
OnNetworkTapListener
¶ Interface for all listeners for clicks on list items
-
class
PostViewHolder
extends RecyclerView.ViewHolder¶ This ViewHolder is for network_summary, a CardView for networks.
-
public class
OnboardActivity
extends AhoyOnboarderActivity¶ Introduce user to the app through a series of informational screens that end with a button that redirects the user to a login page
-
protected void
onActivityResult
(int requestCode, int response, Intent data)¶ After the user has logged in, this function is called to redirect user to new activity
Parameters: - requestCode – Code that indicates what startActivityForResult call has finished
- response – Response from the completed call
- data – Data returned from the call
-
public class
PostsFrag
extends Fragment¶ Created by Dylan Grosz (dgrosz@stanford.edu) on 11/10/17.
-
public void
onAttach
(Context context)¶ -
Parameters: - context – {@inheritDoc}
-
public void
onCreate
(Bundle savedInstanceState)¶ {@inheritDoc} Also initialize
PostsFrag.settings
andPostsFrag.queue
Parameters: - savedInstanceState – {@inheritDoc}
-
public View
onCreateView
(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)¶ Create user interface and handle clicks on posts by launching
SpecificPostActivity
, which displays more detailed information.Parameters: - inflater – Inflates
R.layout.fragment_posts
into a full user interface that is a child ofcontainer
- container – Parent of created user interface
- savedInstanceState – Not used
Returns: Inflated user interface
- inflater – Inflates
-
public class
RVAdapter
extends RecyclerView.Adapter<RVAdapter.PostViewHolder>¶ Adapter that provides the
Post
s and/orEvent
s of aorg.codethechange.culturemesh.models.Network
to displayed, scrollable lists
-
public
RVAdapter
(List<FeedItem> netPosts, OnItemClickListener listener, Context context)¶ Initialize instance fields with provided parameters
Parameters: - netPosts – List of objects to represent in the displayed list
- listener – Listener to handle clicks on list tiems
- context –
Context
in which the list will be displayed
-
public int
getItemCount
()¶ Get the number of items to display
Returns: Number of items in the list of items to display ( RVAdapter.netPosts
)
-
public void
onBindViewHolder
(PostViewHolder pvh, int i)¶ Link the provided
PostViewHolder
to an object in the listRVAdapter.netPosts
, which is used to fill the fields in thePostViewHolder
Parameters: - pvh – Item in the displayed list whose fields to fill with information
- i – Index of object in
RVAdapter.netPosts
that will serve as the source of information to fill into the displayed list item
-
public PostViewHolder
onCreateViewHolder
(ViewGroup parent, int viewType)¶ Create a new
PostViewHolder
from aView
created by inflating the layout described byR.layout.post_view
.Parameters: - parent – Parent for created
View
used to createPostViewHolder
- viewType – Not used
Returns: A new
PostViewHolder
for inclusion in the displayed list- parent – Parent for created
-
public interface
OnItemClickListener
¶ Interface listeners for clicks on items must implement
-
static class
PostViewHolder
extends RecyclerView.ViewHolder¶ Stores the
View
elements of each item in the displayed list. Instances of this class are linked to objects inRVAdapter.netPosts
byRVAdapter.onBindViewHolder(PostViewHolder,int)
, which fills the fields with content from the object.
-
RelativeLayout
comment1Layout
¶ Layout within which the two displayed comments are defined
-
LinearLayout
eventDetailsLL
¶ Layout within which the details section of the displayed list item is defined
-
ConstraintLayout
layout
¶ Layout within which the displayed list item is defined
-
public void
bind
(FeedItem item, OnItemClickListener listener)¶ Set the displayed list item’s listener that handles clicks to that of the provided listener
Parameters: - item – The clicked-on item which will be passed to the listener’s
OnItemClickListener.onItemClick(FeedItem)
method when the item is clicked - listener – Listener to handle all clicks on items in the list
- item – The clicked-on item which will be passed to the listener’s
-
public class
RVCommentAdapter
extends RecyclerView.Adapter<RVCommentAdapter.PostReplyViewHolder>¶ Adapter that populates a UI list with comments
-
public
RVCommentAdapter
(List<PostReply> comments, OnItemClickListener listener, Context context)¶ Store parameters in instance fields
Parameters: - comments – List of comments to display in scrollable list to user
- listener – Will be called whenever an item is clicked
- context –
Context
within which the list will be displayed
-
public int
getItemCount
()¶ Get the number of comments in the list
Returns: Number of comments in list
-
public void
onBindViewHolder
(PostReplyViewHolder pvh, int i)¶ Fill in the fields of
pvh
with the information stored in thePostReply
at positioni
in the list of commentsParameters:
-
public PostReplyViewHolder
onCreateViewHolder
(ViewGroup parent, int viewType)¶ Create a
PostReplyViewHolder
forparent
with aView
inflated fromR.layout.comment_view
Parameters: - parent –
ViewGroup
within which to create thePostReplyViewHolder
- viewType – Not used
Returns: The
PostReplyViewHolder
associated with the inflatedView
- parent –
-
public interface
OnItemClickListener
¶ Interface implemented by any listener for item clicks
-
static class
PostReplyViewHolder
extends RecyclerView.ViewHolder¶ Holder for the parts of each
View
in the list
-
ConstraintLayout
layout
¶ Layout within which the list item components are arranged
-
public abstract class
RedirectableAppCompatActivity
extends AppCompatActivity¶ Superclass for all classes that support redirection instructions from the activity they are launched from. For instance, if
A
launchesB
, which is a subclass ofRedirectableAppCompatActivity
,A
can giveB
instructions to launchC
when it finishes. If insteadZ
launchesB
, it can giveB
instructions to next launchX
.
-
protected void
onDestroy
()¶ {@inheritDoc} Also uses the extras in the launching
Intent
to decide which Activity to launch nextSee also:
Redirection
-
public class
Redirection
¶ Classes that extend this one can be sent information when launched regarding where the user should be directed next.
-
static final String
LAUNCH_ON_FINISH_EXTRA
¶ Key in
android.content.Intent
’s extras whose argument specifies the Class of the Activity to launch when finishingSee also:
Intent.getExtras()
-
static final String
PASS_ON_FINISH_EXTRA
¶ Key in
android.content.Intent
’s extras whose argument specifies aandroid.os.Bundle
whose contents will be passed as extras via the Intent called on finishing
-
public class
SearchAdapter
<T extends Listable> extends ArrayAdapter<T> implements Filterable¶ Populates a displayed list with items
Parameters: - <T> – Type of item to put in the list
-
public
SearchAdapter
(Context context, int resource, int listViewID, List<T> items)¶ Initialize instance fields with provided parameters
Parameters: - context – {@inheritDoc}
- resource – {@inheritDoc}
- listViewID – Identifier for list the adapter will populate
- items – {@inheritDoc}
-
public void
addAll
(Collection<? extends T> collection)¶ Add all items in a
Collection
to the list of items the adapter displays in the listParameters: - collection – Items to add to the list
-
public T
getItem
(int position)¶ Get the item associated with the list entry at a certain position
Parameters: - position – Position of list item
Returns: The object represented at the specified position
-
class
HolderItem
¶ Keeping views accessible saves calls to findViewById, which is a performance bottleneck. This is exactly why we have RecyclerView!
-
public class
SettingsActivity
extends DrawerActivity implements NetworkSummaryAdapter.OnNetworkTapListener¶ Screen that displays the current user’s profile and let’s them update it
-
final long
MAX_PIXELS
¶ The max number of pixels for an image given the image. Each pixel is 8 bytes large (according to RGBA_F16), and a MB is 2^20 bytes
-
ScrollView
scrollView
¶ The user whose profile is displayed and being edited
-
protected void
onActivityResult
(int requestCode, int resultCode, Intent data)¶ This function is overridden to handle image selection. Inspiration from http://www.tauntaunwonton.com/blog/2015/1/21/simple-posting-of-multipartform-data-from-android
Parameters: - requestCode – PICK_IMAGE if we asked them to choose an image from the gallery.
- resultCode – {@inheritDoc}
- data – Hopefully, the URI.
-
protected void
onCreate
(Bundle savedInstanceState)¶ Setup the user interface with the layout defined in
R.layout.activity_settings
. Also initialize instance fields for UI fields with the elements defined in the layout file. Fill the fields with the current profile (fetched usingAPI.Get.user(RequestQueue,long,Response.Listener)
). Link listeners to buttons and the displays ofNetwork
s to handle interactions.Parameters: - savedInstanceState – {@inheritDoc}
-
public void
onItemClick
(View v, Network network)¶ Handle what happens when a user clicks on a
Network
. Right now, nothing is done.Parameters: - v – {@inheritDoc}
- network – {@inheritDoc}
-
public void
onStop
()¶ This ensures that we are canceling all network requests if the user is leaving this activity. We use a RequestFilter that accepts all requests (meaning it cancels all requests)
-
void
resetAdapter
()¶ Reset the adapter by clearing it and then populating it with new information from
API.Get.userNetworks(RequestQueue,long,Response.Listener)
,API.Get.networkPostCount(RequestQueue,long,Response.Listener)
, andAPI.Get.networkUserCount(RequestQueue,long,Response.Listener)
.
Updates user info via PUT request to server.
Parameters: - settings – SharedPreferences instance to save email.
-
public class
SpecificPostActivity
extends AppCompatActivity implements FormatManager.IconUpdateListener¶ Displays a particular
Post
along with its comments (PostReply
). Also allows the user to add comments.
-
ImageButton
boldButton
¶ Buttons for inline markup of the text of the reply
-
ListenableEditText
commentField
¶ Field for the user to enter a comment
-
boolean
editTextOpened
¶ Whether the “window” to write a reply is open. Starts off
false
-
FormatManager
formatManager
¶ Manages markup of the text of the reply
-
FrameLayout
loadingOverlay
¶
-
ProgressBar
progressBar
¶ Progress bar for displaying the progress of network operations
-
SparseArray<ImageButton>
toggleButtons
¶ Tracks whether the inline markup buttons have been toggled to “on”
-
ConstraintLayout
writeReplyView
¶ Layout within which the compose reply UI elements are arranged
-
void
closeEditTextView
()¶ When the user selects out of the text field, the view will shrink back to its original position.
-
void
genResizeAnimation
(int oldSize, int newSize, ConstraintLayout layout)¶ This little helper handles the animation involved in changing the size of the write reply view.
Parameters: - oldSize – start height, in pixels.
- newSize – final height, in pixels.
- layout – writeReplyView
-
protected void
onCreate
(Bundle savedInstanceState)¶ Create the user interface from the layout defined by
R.layout.activity_specific_post
. Initialize instance fields with the UI elements defined in the layout. Setup listeners to handle loading more comments, clicks to post replies, and load thePost
to display.Parameters: - savedInstanceState – {@inheritDoc}
-
protected void
onStop
()¶ This ensures that we are canceling all network requests if the user is leaving this activity. We use a RequestFilter that accepts all requests (meaning it cancels all requests)
-
void
openEditTextView
()¶ This function animates the bottom view to expand up, allowing for a greater text field as well as toggle buttons.
-
public void
updateIconToggles
(SparseBooleanArray formTogState, SparseArray<int[]> toggleIcons)¶ Update whether an icon has been “toggled”, or selected
Parameters: - formTogState – a SparseBooleanArray (HashMap) with int as key and boolean as value key: int id of toggleButton View we are using. value: true if toggled, false if not toggled.
- toggleIcons – a SparseArray (HashMap) with int as key and int[] as value. key: int id of toggleButton View we are using.
-
public class
StartActivity
extends AppCompatActivity¶ Transparent
android.app.Activity
that is the default Activity. It is the one launched when the app first starts, and it is the farthest back the “back” button (on the phone, not in the app) can go before leaving the app. It redirects the user based on their onboarding and login status.
-
protected void
onResume
()¶ Whenever this screen becomes “visible”, immediately redirect the user to
TimelineActivity
if they have a selected network and are logged in. If they are logged-in without a selected network, redirect them toExploreBubblesOpenGLActivity
. If they are logged-out, redirect them toOnboardActivity
.
-
public class
TimelineActivity
extends DrawerActivity implements DrawerActivity.WaitForSubscribedList¶ Show a feed of
org.codethechange.culturemesh.models.Post
s andorg.codethechange.culturemesh.models.Event
s for the currently selectedNetwork
-
static SharedPreferences
settings
¶ The app’s preferences
-
void
animateFAB
()¶ This function controls the animation for the FloatingActionButtons. When the user taps the pencil icon, two other floating action buttons rise into view - create post and create event. The
-
protected void
createDefaultNetwork
()¶ Use API methods to fetch details of the user’s selected network. Then setup activity to display that network’s feed.
-
protected void
createNoNetwork
()¶ If the user has no selected network, direct them to
ExploreBubblesOpenGLActivity
-
public void
onBackPressed
()¶ Handle the back button being pressed. If the drawer is open, close it. If the user has scrolled down the feed, return it to the start. Otherwise, go back to the previous activity.
-
protected void
onCreate
(Bundle savedInstanceState)¶ Setup user interface using layout defined in
R.layout.activity_timeline
and initialize instance fields with that layout’s fields (elements)Parameters: - savedInstanceState – {@inheritDoc}
-
public boolean
onOptionsItemSelected
(MenuItem item)¶ -
Parameters: - item – {@inheritDoc}
Returns: If
item
is selected or if it has the same ID asR.id.action_settings
, returntrue
. Otherwise, return the result ofDrawerActivity.onOptionsItemSelected(MenuItem)
with parameteritem
-
protected void
onStart
()¶ Check if user has selected a network to view, regardless of whether the user is subscribed to any networks yet. Previously, we checked if the user joined a network, and instead navigate the user to ExploreBubbles. This is not ideal because if a user wants to check out a network before joining one, then they will be unable to view the network. Also calls
DrawerActivity.onStart()
-
public void
onSubscribeListFinish
()¶ If the user is subscribed to the network, they are able to write posts and events. If the user is not subscribed to the network, there should be a pretty button for them that encourages the user to join the network. This control flow relies on checking if the user is subscribed to a network or not, which requires an instantiated subscribedNetworkIds set in DrawerActivity. This set is instantiated off the UI thread, so we need to wait until that thread completes. Thus, this function is called by DrawerActivity after the network thread completes.
-
public static class
FilterDialogFragment
extends DialogFragment¶ This dialog allows us to filter out native/twitter posts from the feed
-
public class
UsersListAdapter
extends RecyclerView.Adapter<UsersListAdapter.ViewHolder>¶ This Adapter is used for viewing the subscribed users of a network.
-
public int
getItemCount
()¶ Get the number of items in the list of objects to display
Returns: Number of items in list to display
-
public void
onBindViewHolder
(ViewHolder holder, int position)¶ Fill the name and profile picture fields of
holder
with the contents of an item inUsersListAdapter.users
.Parameters: - holder –
ViewHolder
whose fields to fill with information - position – Index of item in list of users to use as source of information for filling
- holder –
-
public ViewHolder
onCreateViewHolder
(ViewGroup parent, int viewType)¶ Create a new
UsersListAdapter.ViewHolder
from aView
inflated fromR.layout.user_list_item
and with parentparent
Parameters: - parent – Parent for the
View
used to create the newUsersListAdapter
- viewType – Not used.
Returns: The created
UsersListAdapter.ViewHolder
- parent – Parent for the
-
class
ViewHolder
extends RecyclerView.ViewHolder¶ Holder of UI elements that compose each element of the displayed list
-
public class
ViewProfileActivity
extends AppCompatActivity¶ Displays the profile of a user other than the currently-logged-in one
-
public static final String
SELECTED_USER
¶ Key for extra in
android.content.Intent
s that specifies the user whose profile is to be displayed. This should be included in the intent that launches this activity.
-
FrameLayout
loadingOverlay
¶
-
protected void
onCreate
(Bundle savedInstanceState)¶ Setup the user interface using the layout defined in
R.layout.activity_view_profile
and configure the various tabs. Initialize instance fields with the elements of theandroid.view.View
created from the layout and fill the UI fields with the content of the profile usingAPI.Get.user(RequestQueue,long,Response.Listener)
Parameters: - savedInstanceState – {@inheritDoc}
-
class
ContributionsPager
extends FragmentStatePagerAdapter¶ This PagerAdapter returns the correct fragment based on which list the user wishes to see. This could be seeing the list of networks the user is subscribed to, the list of posts the user has written, or the list of events the user has attended.
-
ContributionsPager
(FragmentManager fm)¶
-
public class
ViewUsersModalSheetFragment
extends BottomSheetDialogFragment¶ Created By Drew Gregory on 03/30/18. This shows the subscribed users in the network using a modal bottom sheet https://material.io/guidelines/components/bottom-sheets.html#bottom-sheets-modal-bottom-sheets Also, inspiration from the following blog posts: - https://android-developers.googleblog.com/2016/02/android-support-library-232.html - https://code.tutsplus.com/articles/how-to-use-bottom-sheets-with-the-design-support-library–cms-26031
org.codethechange.culturemesh.models¶
-
public class
City
extends Place¶ A
City
is a specific kind ofPlace
that stores the ID and name of a city. It can also store the names and IDs of the city’s country and region, but this is not mandatory. If any geographical descriptor (e.g. city, region, or country) is not specified, its name will be stored asPlace.NOWHERE
, but this constant should not be used by clients. Note that thecity
descriptor is mandatory.
-
public
City
(long cityId, long regionId, long countryId, String cityName, String regionName, String countryName, Point latLng, long population, String featureCode)¶ Initialize instance fields and instance fields of superclasses based on provided arguments For creating cities that have city, region, and country all specified.
Parameters: - cityId – ID of city
- regionId – ID of city’s region
- countryId – ID of country’s region
- cityName – Name of city
- regionName – Name of region city lies within
- countryName – Name of country city lies within
- latLng – Latitude and longitude coordinates of city
- population – Population of the city
- featureCode – Feature code of the city
-
public
City
(long cityId, long regionId, String cityName, String regionName, Point latLng, long population, String featureCode)¶ Initialize instance fields and instance fields of superclasses based on provided arguments. For creating cities that have no country descriptor, but do have specified regions.
Parameters: - cityId – ID of city
- regionId – ID of city’s region
- cityName – Name of city
- regionName – Name of region city lies within
- latLng – Latitude and longitude coordinates of city
- population – Population of the city
- featureCode – Feature code of the city
-
public
City
(long cityId, String cityName, Point latLng, long population, String featureCode)¶ Initialize instance fields and instance fields of superclasses based on provided arguments For creating cities that have no region nor country descriptor
Parameters: - cityId – ID of city
- cityName – Name of city
- latLng – Latitude and longitude coordinates of city
- population – Population of the city
- featureCode – Feature code of the city
-
public
City
(JSONObject json)¶ Initialize instance fields and those of superclass based on provided JSON This class extracts the following fields, if they are present:
country_name
andregion_name
. It requires that the keyname
exist, as its value will be used as the City’s nameParameters: - json – JSON object describing the city to create
Throws: - JSONException – May be thrown in response to an invalidly formatted JSON object
-
public String
getFullName
()¶ Get a name for the city that lists all available geographic descriptor names. For example,
Washington, D.C.
would be expressed asWashington, D.C., United States
, whileSan Francisco
would be expressed asSan Francisco, California, United States
.Returns: Name of city that includes all available geographic descriptors
-
public static City
newOnlyMissingRegion
(long cityId, long countryId, String cityName, String countryName, Point latLng, long population, String featureCode)¶ Return
City
object with fields initialized with provided parameters For creating cities that are only missing the region descriptor This unusual pseudo-constructor is required to avoid ambiguity between constructorsParameters: - cityId – ID of city
- countryId – ID of country’s region
- cityName – Name of city
- countryName – Name of country city lies within
- latLng – Latitude and longitude coordinates of city
- population – Population of the city
- featureCode – Feature code of the city
Returns: City object that has been initialized
-
public class
Country
extends Place¶ A
Country
is a specific kind ofPlace
that stores the ID and name of a country. No instance field should ever be set toPlace.NOWHERE
.
-
public
Country
(long id, String name, Point latLng, long population, String featureCode, String isoA2)¶ Initialize instance fields and those of superclass with provided parameters
Parameters: - id – ID of country
- name – Name of country
- latLng – Latitude and longitude coordinates of the region
- population – Population of the region
- featureCode – Region’s feature code
- isoA2 – 2-Letter ISO country code
-
public
Country
(JSONObject json)¶ Initialize instance fields and those of superclass based on provided JSON It requires that the key
name
exist, as its value will be used as the country’s nameParameters: - json – JSON object describing the country to create
Throws: - JSONException – May be thrown in response to invalid JSON object
-
public String
getFullName
()¶ Get name of country, which is suitable for display in UI.
Returns: Name of country, abbreviated if necessary to have a maximum length of org.codethechange.culturemesh.Listable.MAX_CHARS
.See also:
org.codethechange.culturemesh.Listable
-
public abstract class
DatabaseLocation
extends Location¶ Superclass for Locations that will be stored in the database. Since the instance field names are used directly as column names in the database, a single class cannot be used for both From and Near locations (the column names would conflict). Therefore, two separate classes,
FromLocation
andNearLocation
are used. They are nearly identical, however, so this superclass holds methods common to both. It also imposes requirements on them to ensure that those methods can function. The database will store the IDs of the city, region, and country.
-
public
DatabaseLocation
(long countryId, long regionId, long cityId)¶ Constructor that passes all parameters to superclass constructor
Parameters: - countryId – ID of country
- regionId – ID of region
- cityId – ID of city
-
public
DatabaseLocation
(JSONObject json)¶ Constructor that passes all parameters to superclass constructor
Parameters: - json – JSON object that defines the location. See superclass constructor documentation.
Throws: - JSONException – May be thrown for improperly formatted JSON
-
public class
DatabaseNetwork
¶ This class is solely for storing the bare, ID-only form of a network in the database. After being retrieved from the database or received from a network request, it should immediately be used to create a
Network
object, with the additional information that comes with. Storing only IDs in the database makes theDatabaseNetwork.nearLocation
,DatabaseNetwork.fromLocation
andDatabaseNetwork.languageId
references pointers to database entries with more information. This reduces the risk of conflicting information and reduces the overhead of updating data in more than one spot in the database.
-
public FromLocation
fromLocation
¶ The location where the users of this network are from. It may be
null
to indicate that no location is specified only ifDatabaseNetwork.isLanguageBased
isfalse
-
public boolean
isLanguageBased
¶ Denotes whether this network’s from attribute is based on where an individual is from or on what language they speak.
true
: Based on what language they speakfalse
: Based on what location they are from
-
public long
languageId
¶ The ID of the language the users of this network speak. It may be set to
-1
to indicate no language being specified only ifDatabaseNetwork.isLanguageBased
isfalse
-
public NearLocation
nearLocation
¶ The location where the users of this network currently reside. It must not be null.
-
public
DatabaseNetwork
()¶ Empty constructor for database use only. This should never be called by our code.
-
public
DatabaseNetwork
(NearLocation nearLocation, FromLocation fromLocation, long id)¶ Create a new
DatabaseNetwork
for a network of people who come from the same areaParameters: - nearLocation – Where the network’s members currently reside
- fromLocation – Where the network’s members are from
- id – ID for this network
-
public
DatabaseNetwork
(NearLocation nearLocation, long langId, long id)¶ Create a new
DatabaseNetwork
for a network of people who speak the same languageParameters: - nearLocation – Where the network’s members currently reside
- langId – ID for the language the network’s members speak
- id – ID for this network
-
public
DatabaseNetwork
(JSONObject json)¶ If the key location_cur is present (old JSON version): Initialize instance fields with the data in the provided JSON. The following keys are mandatory and used:
location_cur
, whose value is expected to be a JSON describing aNearLocation
object and can be passed toNearLocation.NearLocation(JSONObject)
, andnetwork_class
, whose value is expected to be either0
, indicating a location-based network, or1
, indicating a language-based network. If the network is language-based, they keylanguage_origin
must exist with a value of a JSON object containing a keyid
whose value is the ID of aLanguage
. If the network is location-based, the keylocation_origin
must exist and have a value of a JSON object representing aFromLocation
that can be passed toFromLocation.FromLocation(JSONObject)
. NOTE: This JSON format is deprecated and should not be used if possible. If the key location_cur is not present (new JSON version): Initialize instance fields with the data in the provided JSON. The following keys are mandatory and used: All keys required byNearLocation.NearLocation(JSONObject)
and the keynetwork_class
, whose value is expected to be either_l
, indicating a language-based network, or one ofcc
,rc
, andco
, indicating a location-based network. If the network is language-based, the keyid_language_origin
must exist with a value of the ID of aLanguage
. If the network is location-based, all keys required byFromLocation.FromLocation(JSONObject)
must be present.Parameters: - json – JSON object describing the network in terms of IDs
Throws: - JSONException – May be thrown in response to improperly formatted JSON
-
public boolean
isLanguageBased
()¶ Check whether this network is of people who speak the same language
Returns: true
if the network is defined in terms of language,false
otherwise
-
public class
Event
extends FeedItem implements Serializable, Putable, Postable¶ Describes an event like those shared in
Network
s
-
public static final String
NOWHERE
¶ Value other classes should pass to this class and should expect to receive from this class to represent the portions of addresses that are not a part of the address. Note that
Event.getAddress()
uses this constant only when the entire address is missing.
-
public String
description
¶ User-generated description of the event. May contain formatting from
org.codethechange.culturemesh.FormatManager
.
-
public
Event
(long id, long networkId, String title, String description, String timeOfEvent, long author, String addressLine1, String addressLine2, String city, String region, String country)¶ Construct an Event object from the provided parameters.
Parameters: - id – Unique identifier for the event
- networkId – Unique identifier for the
Network
the event is a part of - title – User-generated title for the event
- description – User-generated description of the event
- timeOfEvent – Date and time of the event. Must strictly conform to the format
yyyy-MM-ddTHH:mm:ss.SSSZ
. - author – Unique identifier for the
User
creating theEvent
- addressLine1 – Optional first line of the address.
Event.NOWHERE
if absent. - addressLine2 – Optional second line of the address.
Event.NOWHERE
if absent. - city – Optional city portion of the address.
Event.NOWHERE
if absent. - region – Optional region portion of the address.
Event.NOWHERE
if absent. - country – Optional country portion of the address.
Event.NOWHERE
if absent.
-
public
Event
()¶ Empty constructor that does nothing to initialize any instance fields. For database use only.
-
public
Event
(JSONObject json)¶ Create a new Event object from a JSON representation that conforms to the following format:
{ "id": 0, "id_network": 0, "id_host": 0, "date_created": "string", "event_date": "2018-06-23T04:39:42.600Z", "title": "string", "address_1": "string", "address_2": "string", "country": "string", "city": "string", "region": "string", "description": "string" }
Note that
date_created
is not used and may be omitted. Empty address fields should benull
.Parameters: - json – JSON representation of the
Event
to be created
Throws: - JSONException – May be thrown if an improperly formatted JSON is provided
- json – JSON representation of the
-
public String
getAddress
()¶ Generate a formatted form of the address for the event that is suitable for display to user.
Returns: UI-suitable form of the address where the event will take place. Address portions (line1, line2, city, region, and country) are separated by commas, and missing portions are excluded. Example: 123 Any Street, New York, New York
. The address portions are user-generated, so this String may not describe a valid address. If no address is specified (i.e. if all address portions are missing), theEvent.NOWHERE
constant is returned.
-
public JSONObject
getPostJson
()¶ Create a JSON representation of the object that conforms to the following format:
{ "id_network": 0, "id_host": 0, "event_date": "2018-07-21T15:10:30.838Z", "title": "string", "address_1": "string", "address_2": "string", "country": "string", "city": "string", "region": "string", "description": "string" }
This is intended to be the format used by the
/event/new
POST endpoint.Throws: - JSONException – Unclear when this would be thrown
Returns: JSON representation of the object
-
public JSONObject
getPutJson
()¶ Create a JSON representation of the object that conforms to the following format:
{ "id": 0, "id_network": 0, "id_host": 0, "event_date": "2018-07-21T15:10:30.838Z", "title": "string", "address_1": "string", "address_2": "string", "country": "string", "city": "string", "region": "string", "description": "string" }
This is intended to be the format used by the
/event/new
PUT endpoint.Throws: - JSONException – Unclear when this would be thrown
Returns: JSON representation of the object
-
public class
FeedItem
¶ Superclass for Posts and Events that mandates they both have a list of PostReply objects that can be displayed in a feed.
-
public class
FromLocation
extends DatabaseLocation¶ Wrapper for
DatabaseLocation
that is for From locations. See the documentation forDatabaseLocation
for information as to why this redundancy is necessary. All of these instance fields will be stored in the local cached database.
-
public static final String
CITY_ID_KEY
¶ Constant that holds the JSON key whose value will be the ID of the city (
City.cityId
) in communications with the server.See also:
Location.Location(JSONObject,String,String,String)
-
public static final String
COUNTRY_ID_KEY
¶ Constant that holds the JSON key whose value will be the ID of the country (
Country.countryId
) in communications with the server.See also:
Location.Location(JSONObject,String,String,String)
-
public static final String
REGION_ID_KEY
¶ Constant that holds the JSON key whose value will be the ID of the region (
Region.regionId
) in communications with the server.See also:
Location.Location(JSONObject,String,String,String)
-
public long
from_city_id
¶ Mirrors the
Location.cityId
inLocation
to avoid collisions in the databaseSee also:
DatabaseLocation
-
public long
from_country_id
¶ Mirrors the
Location.countryId
inLocation
to avoid collisions in the databaseSee also:
DatabaseLocation
-
public long
from_region_id
¶ Mirrors the
Location.regionId
inLocation
to avoid collisions in the databaseSee also:
DatabaseLocation
-
public
FromLocation
(long cityId, long regionId, long countryId)¶ Initialize instance fields with provided parameters
Parameters: - cityId – ID of city
- regionId – ID of region
- countryId – ID of country
-
public
FromLocation
(JSONObject json)¶ Initializes instance fields by passing JSON to
Location.Location(JSONObject,String,String,String)
and then initializing instance fields usingFromLocation.initialize()
Parameters: - json – JSON object describing the location
Throws: - JSONException – May be thrown in response to improperly formatted JSON
-
public
FromLocation
(JSONObject json, boolean distinguisher)¶ Initializes instance fields by passing JSON to
Location.Location(JSONObject)
)} and then initializing instance fields usingFromLocation.initialize()
Parameters: - json – JSON object describing the location
Throws: - JSONException – May be thrown in response to improperly formatted JSON
-
public class
Language
implements Serializable, Listable¶ Represents a language that may be spoken by users. It may be included as part of the definition of a
Network
or as an attribute of aUser
, for example.
-
public
Language
(long id, String name, int numSpeakers)¶ Create a new
Language
object with the provided propertiesParameters: - id – Unique identifier for the language. The same ID must be used everywhere
- name – Human-readable name of the language. This will be displayed to users. It must also be unique, as it is passed in API calls.
- numSpeakers – The number of Culturemesh users who speak the language
-
public
Language
(JSONObject json)¶ Create a new
Language
from the JSON produced by an API call. The JSON must conform to the following format:{ "lang_id": 0, "name": "string", "num_speakers": 0, "added": 0 }
Note that the
added
key is not used and therefore optional.Parameters: - json – JSON representation of the language to create.
Throws: - JSONException – May be thrown for an improperly formatted JSON
-
public String
getListableName
()¶ Get a descriptive representation of the language suitable for display to user
Returns: Name of the language, abbreviated to be at most Listable.MAX_CHARS
characters long.
-
public long
getNumUsers
()¶ Get the number of users who speak the language
Returns: Number of users who speak the language
-
public class
Location
implements Serializable, Listable¶ This object stores only the city, region, and country ID values, so it acts as a pointer to the more detailed information for the location in each City, Region, and Country’s database entries or network information. No instance of this class should have
countryId
,regionId
, andcityId
all equal toNOWHERE
. This should only be possible by mis-using the JSON constructor or by supplying-1
as an ID. Neither should ever be done.Location (IDs only) / / / / Place (Abstract) DatabaseLocation (Abstract) (Full Info) (IDs) / | / / | NearLocation FromLocation City Region Country (Wrappers for DatabaseLocation) (Specific cases of Place)
-
public static final int
CITY
¶ Represents a type of
Location
that has a city defined.See also:
Location.getType()
-
public static final int
COUNTRY
¶ Represents a type of
Location
that has only a country defined.See also:
Location.getType()
-
protected static final int
NOWHERE
¶ These constants are used to identify the type of location being stored. See the documentation for
getType
for more.NOWHERE
isprotected
because it should never be used by clients. It is only for subclasses to denote empty IDs. Creating locations with empty IDs should be handled by subclass constructors or methods.
-
public static final int
REGION
¶ Represents a type of
Location
that has a region defined but not a city.See also:
Location.getType()
-
public static final int
URL_NULL_ID
¶ The value to be transmitted to the API in place of a missing country, region, or city ID
-
public long
countryId
¶ These instance fields store the IDs of the city, region, and country defining the location They can be
private
because a plainLocation
object should not need to be stored in the database.
-
public String
locationName
¶ This is is only used for other searching in
org.codethechange.culturemesh.FindNetworkActivity
. Do not use this field anywhere else.
-
public
Location
(long countryId, long regionId, long cityId)¶ Initializes ID instance fields using the provided IDs
Parameters: - countryId – ID of country
- regionId – ID of region
- cityId – ID of city
-
public
Location
(JSONObject json)¶ Initializes ID instance fields using the provided JSON object If present, the values of the keys
city_id
,region_id
, andcountry_id
will be used automatically. Depending on the presence of those keys, the value of the keyid
will be used to fill the instance field for the JSON type. SeegetJsonType
for more. This constructor is designed to be used when creatingPlace
s. Precondition: The JSON must be validly formatted, with examples inAPI.java
Parameters: - json – JSON object containing the country, region, and city IDs
Throws: - JSONException – May be thrown if the JSON is improperly formatted
-
public
Location
(JSONObject json, String cityIdKey, String regionIdKey, String countryIdKey)¶ Initializes ID instance fields using the provided JSON object. The keys extracted are provided as parameters, but those keys need not exist in the JSON. Any missing keys will be treated as if the location does not have such a geographic identifier. This may produce an invalid location, and the JSON is followed blindly. Precondition: JSON must describe a valid location
Parameters: - json – JSON that describes the location to create
- cityIdKey – The key that, if present in the JSON, has a value of the ID of the city
- regionIdKey – The key that, if present in the JSON, has a value of the ID of the region
- countryIdKey – The key that, if present in the JSON, has a value of the ID of the country
Throws: - JSONException – May be thrown in the case of an invalid JSON
-
public long
getCityId
()¶ Getter for the city ID, which may return
NOWHERE
, sohasCityId
should be used to check firstReturns: The city ID
-
public long
getCountryId
()¶ Getter for the country ID, which may return
NOWHERE
, sohasCountryId
should be used to check firstReturns: The country ID
-
protected long
getDatabaseId
()¶ Find the ID that should be used as the
PrimaryKey
for a database. It is the ID of the most specific geographical descriptor with an ID that is notNOWHERE
. WARNING: The returned ID is NOT guaranteed to be uniqueReturns: ID for use as PrimaryKey
in a database
-
public FromLocation
getFromLocation
()¶ Transform a
Location
into aFromLocation
Returns: A FromLocation
with the same IDs as theLocation
object whose method was called
-
public String
getListableName
()¶ Get a UI-ready name for the Location
Returns: Name for the Location that is suitable for display to the user. Abbreviated to be a maximum of Listable.MAX_CHARS
characters long.
-
public NearLocation
getNearLocation
()¶ Transform a
Location
into aNearLocation
Returns: A NearLocation
with the same IDs as theLocation
object whose method was called
-
public long
getRegionId
()¶ Getter for the region ID, which may return
NOWHERE
, sohasRegionId
should be used to check firstReturns: The region ID
-
public int
getType
()¶ The most specific ID that is not
NOWHERE
determines the location’s type, even if more general IDs areNOWHERE
. For example, ifregionId = 0
andcountryId = cityId = NOWHERE
, the type would beREGION
Returns: Location’s type as CITY
,REGION
, orCOUNTRY
-
public boolean
hasCityId
()¶ Check if the city ID is specified (i.e. not
NOWHERE
)Returns: true
if the city ID is specified,false
otherwise
-
public boolean
hasCountryId
()¶ Check if the country ID is specified (i.e. not
NOWHERE
)Returns: true
if the country ID is specified,false
otherwise
-
public boolean
hasRegionId
()¶ Check if the region ID is specified (i.e. not
NOWHERE
)Returns: true
if the region ID is specified,false
otherwise
-
public String
urlParam
()¶ Represent the
Location
in a form suitable for use as the value of a key passed in a URL parameter to the API. Specifically, it returns the country, region, and city IDs separated by commas and in that order. The commas are escaped with the UTF-8 scheme and any missing IDs are replaced with theLocation.URL_NULL_ID
constant, which is understood by the API as signifyingnull
.Returns: An API-compatible representation suitable for use as the value in a URL parameter
-
public class
NearLocation
extends DatabaseLocation¶ Wrapper for
DatabaseLocation
that is for Near locations. See the documentation forDatabaseLocation
for information as to why this redundancy is necessary. All of these instance fields will be stored in the local cached database.
-
public static final String
CITY_ID_KEY
¶ Constant that holds the JSON key whose value will be the ID of the city (
City.cityId
) in communications with the server.See also:
Location.Location(JSONObject,String,String,String)
-
public static final String
COUNTRY_ID_KEY
¶ Constant that holds the JSON key whose value will be the ID of the country (
Country.countryId
) in communications with the server.See also:
Location.Location(JSONObject,String,String,String)
-
public static final String
REGION_ID_KEY
¶ Constant that holds the JSON key whose value will be the ID of the region (
Region.regionId
) in communications with the server.See also:
Location.Location(JSONObject,String,String,String)
-
public long
near_city_id
¶ Mirrors the
Location.cityId
inLocation
to avoid collisions in the databaseSee also:
DatabaseLocation
-
public long
near_country_id
¶ Mirrors the
Location.countryId
inLocation
to avoid collisions in the databaseSee also:
DatabaseLocation
-
public long
near_region_id
¶ Mirrors the
Location.regionId
inLocation
to avoid collisions in the databaseSee also:
DatabaseLocation
-
public
NearLocation
(long cityId, long regionId, long countryId)¶ Initialize instance fields with provided parameters
Parameters: - cityId – ID of city
- regionId – ID of region
- countryId – ID of country
-
public
NearLocation
(JSONObject json)¶ Initializes instance fields by passing JSON to
Location.Location(JSONObject,String,String,String)
and then initializing instance fields usingNearLocation.initialize()
Parameters: - json – JSON object describing the location
Throws: - JSONException – May be thrown in response to improperly formatted JSON
-
public
NearLocation
(JSONObject json, boolean distinguisher)¶ Initializes instance fields by passing JSON to
Location.Location(JSONObject)
and then initializing instance fields usingNearLocation.initialize()
Parameters: - json – JSON object describing the location
- distinguisher – Useless value used to distinguish from
NearLocation.NearLocation(JSONObject)
Throws: - JSONException – May be thrown in response to improperly formatted JSON
-
public class
Network
implements Serializable, Postable¶ This class stores all the information related to a network. It is fully expanded, meaning that its instance fields like
Network.nearLocation
store expanded objects (i.e.Place
, not the stripped-down forms for database storage.
-
public DatabaseNetwork
getDatabaseNetwork
()¶ Get a
DatabaseNetwork
with the IDs stored by theNetwork
from which the method is called.Returns: The DatabaseNetwork
associated with thisNetwork
-
public JSONObject
getPostJson
()¶ Generate a JSON representation of the object suitable for use in POST requests. Wrapper for
Network.toJSON()
.Throws: - JSONException – May be thrown if something that should be a value in the JSON is not a valid value in the JSON format.
Returns: JSON that can be passed to the server in the body of a POST request
See also:
Network.toJSON();
-
public boolean
isLanguageBased
()¶ Check whether this network is of people who speak the same language
Returns: true
if the network is defined in terms of language,false
otherwise
-
public boolean
isLocationBased
()¶ Check whether this network is of people who come from the same place
Returns: true
if the network is defined by where members are from,false
otherwise
-
public JSONObject
toJSON
()¶ Generate a JSON describing the object. The JSON will conform to the following format:
{ "id_city_cur": 0, "city_cur": "string", "id_region_cur": 0, "region_cur": "string", "id_country_cur": 0, "country_cur": "string", "id_city_origin": 0, "city_origin": "string", "id_region_origin": 0, "region_origin": "string", "id_country_origin": 0, "country_origin": "string", "id_language_origin": 0, "language_origin": "string", "network_class": "string" }
where missing IDs are passed as
Location.NOWHERE
. This format is suitable for submission to the server using the/network/new
POST endpoint.Throws: - JSONException – Unclear when this would be thrown
Returns: JSON representation of the object
-
public abstract class
Place
extends Location implements Listable, Serializable¶ A
Place
is aLocation
with more information. While aLocation
stores only city, region, and country IDs,Place
also stores the areas position (latitude and longitude), population, and feature code.Place
is abstract, and some examples of its subclasses are:City
,Region
, andCountry
. Created by Drew Gregory on 2/23/18. This is the superclass for cities, regions, and countries.
-
protected static final String
NOWHERE
¶ The
NOWHERE
constant is used internally by this hierarchy as the name of a location’s city, region, or country when that geographic identifier is not specified. For example, Washington D.C. has no state (i.e. region), so its region might be stored asNOWHERE
. This should never be used by clients. Instead, creating such places should be done through provided constructors or methods.
-
public String
featureCode
¶ Feature code, which is a string describing the type of place represented (e.g. a capital, a religiously important area, an abandoned populated area). See http://www.geonames.org/export/codes.html for more examples.
-
public
Place
(long countryId, long regionId, long cityId, Point latLng, long population, String featureCode)¶ Initialize instance fields with provided parameters. Also calls
Location.Location(long,long,long)
with the provided IDs Postcondition:Place.id
is initialized usingPlace.getDatabaseId()
Parameters: - countryId – ID of country
- regionId – ID of region
- cityId – ID of city
- latLng – Coordinates (latitude and longitude) of location
- population – Population of location
- featureCode – Feature code of location
-
public
Place
(JSONObject json)¶ Initializes ID instance fields using the provided JSON object The following keys must be present and are used to fill the relevant instance fields:
latitude
,longitude
,population
,feature_code
. In addition, the JSON object is passed toLocation.Location(JSONObject)
. See its documentation for details on its requirements.Place.id
is initialized usingPlace.getDatabaseId()
. Precondition: The JSON must be validly formatted, with examples inorg.codethechange.culturemesh.API
Parameters: - json – JSON object to extract initializing information from
Throws: - JSONException – May be thrown for invalidly formatted JSON object
-
public static String
abbreviateForListing
(String toAbbreviate)¶ Abbreviate the provided string by truncating it enough so that, after adding
Listable.ellipses
, the string isListable.MAX_CHARS
characters long. If the string is already shorter thanListable.MAX_CHARS
, it is returned unchanged.Parameters: - toAbbreviate – String whose abbreviated form will be returned
Returns: Abbreviated form of the string. Has a maximum length of
Listable.MAX_CHARS
-
public String
getCityName
()¶ Attempt to get the name of the
City
for thisPlace
. May returnPlace.NOWHERE
.Returns: Name of the City
if one is available, orPlace.NOWHERE
otherwise.
-
public String
getCountryName
()¶ Attempt to get the name of the
Country
for thisPlace
. May returnPlace.NOWHERE
.Returns: Name of the Country
if one is available, orPlace.NOWHERE
otherwise.
-
public String
getFeatureCode
()¶ Get the feature code describing the location. See http://www.geonames.org/export/codes.html for examples.
Returns: Location’s feature code
-
public String
getListableName
()¶ Get a name suitable for display in listings of places, as required to implement
Listable
. This name is created by abbreviating the output ofPlace.getFullName()
and addingListable.ellipses
such that the total length is a no longer thanListable.MAX_CHARS
Returns: Name of Location suitable for display in UI lists. Has a maximum length of Listable.MAX_CHARS
.
-
public long
getNumUsers
()¶ Get the number of users (population) to display in conjunction with the location
Returns: Population of the location
-
public long
getPopulation
()¶ Get the population of the location
Returns: Location’s population
-
public String
getRegionName
()¶ Attempt to get the name of the
Region
for thisPlace
. May returnPlace.NOWHERE
.Returns: Name of the Region
if one is available, orPlace.NOWHERE
otherwise.
-
public class
Post
extends FeedItem implements Serializable, Postable, Putable¶ Represents a post made by a user in a network. A post is arbitrary, formatted text of the user’s choosing.
The
User
who created the post. This may not be present and have to be instantiated fromPost.userId
. Currently, this is handled byorg.codethechange.culturemesh.API
-
public Network
network
¶ The
Network
who created the post. This may not be present and have to be instantiated fromPost.networkId
. Currently, this is handled byorg.codethechange.culturemesh.API
-
public
Post
(long id, long author, long networkId, String content, String imgLink, String vidLink, String datePosted)¶ Create a new post object from the provided parameters. The resulting object will not be fully instantiated (e.g.
Post.author
andPost.network
will benull
.Parameters: - id – Uniquely identifies the post across all of CultureMesh
- author – ID of
User
who created the post - networkId – ID of the
Network
in which the post was made - content – Formatted text that composes the body of the post.
- imgLink – Link to an image associated with the post.
null
if none associated. - vidLink – Link to a video associated with the post.
null
if none associated - datePosted – When the post was created. Must conform to
EEE, dd MMM yyyy kk:mm:ss z
-
public
Post
(JSONObject json)¶ Creates a bare (uninstantiated)
Post
from a JSON that conforms to the below format:{ "id": 0, "id_user": 0, "id_network": 0, "post_date": "string", "post_text": "string", "post_class": 0, "post_original": "string", "vid_link": "string", "img_link": "string" }
Parameters: - json – JSON representation of the
Post
to construct
Throws: - JSONException – May be thrown in response to an improperly formatted JSON
- json – JSON representation of the
-
public JSONObject
getPostJson
()¶ Wrapper for
Post.toJSON()
-
public JSONObject
getPutJson
()¶ Wrapper for
Post.toJSON()
-
public JSONObject
toJSON
()¶ Generate a JSON describing the object. The JSON will conform to the following format:
{ "id_user": 0, "id_network": 0, "post_text": "string", "vid_link": "string", "img_link": "string" }
The resulting object is suitable for use with the
/post/new
endpoint (PUT and POST).Throws: - JSONException – Unclear when this would be thrown
Returns: JSON representation of the object
-
public JSONObject
toJSON
()¶ Generate a JSON describing the object. The JSON will conform to the following format:
{ "id_parent": 0, "id_user": 0, "id_network": 0, "reply_text": "string" }
The resulting object is suitable for use with the
/post/{postId}/reply
POST or PUT endpoints.Throws: - JSONException – Unclear when this would be thrown
Returns: JSON representation of the object
-
public interface
Postable
¶ Classes that implement this interface can be sent in the bodies of requests sent using
org.codethechange.culturemesh.API.Post.model(RequestQueue,Postable,String,String,Response.Listener)
.
-
JSONObject
getPostJson
()¶ Generates a JSON representation of the object that can be used in POST requests to the server. The exact format of the JSON depends upon the specifications of the server API. See the server’s Swagger documentation for more.
Throws: - JSONException – May be thrown if any of the values to include in the JSON are incompatible with the JSON format
Returns: JSON representation of the object suitable for inclusion in the bodies of POST requests
-
public interface
Putable
¶ Classes that implement this interface can be sent in the bodies of requests sent using
org.codethechange.culturemesh.API.Put.model(RequestQueue,Putable,String,String,Response.Listener)
.
-
JSONObject
getPutJson
()¶ Generates a JSON representation of the object that can be used in PUT requests to the server. The exact format of the JSON depends upon the specifications of the server API. See the server’s Swagger documentation for more.
Throws: - JSONException – May be thrown if any of the values to include in the JSON are incompatible with the JSON format
Returns: JSON representation of the object suitable for inclusion in the bodies of PUT requests
-
public class
Region
extends Place¶ A
Region
is a specific kind ofPlace
that stores the ID and name of a region. It can also store the name and ID of the region’s country, but this is not mandatory. If any geographical descriptor (e.g. city, region, or country) is not specified, its name will be stored asPlace.NOWHERE
, but this constant should not be used by clients. Note that theregion
descriptor is mandatory.
-
public String
countryName
¶ Name of the country (may store
Place.NOWHERE
-
public String
regionName
¶ Name of the region (should always be specified and not as
Place.NOWHERE
-
public
Region
(long regionId, long countryId, String regionName, String countryName, Point latLng, long population, String featureCode)¶ Initialize instance fields and those of superclass with provided parameters No parameters should be set to
Place.NOWHERE
orLocation.NOWHERE
For regions with explicitly specified countriesParameters: - regionId – ID of region
- countryId – ID of country
- regionName – Name of region
- countryName – Name of country
- latLng – Latitude and longitude coordinates of the region
- population – Population of the region
- featureCode – Region’s feature code
-
public
Region
(long regionId, String regionName, Point latLng, long population, String featureCode)¶ Initialize instance fields and those of superclass with provided parameters No parameters should be set to
Place.NOWHERE
orLocation.NOWHERE
For regions that have no specified countryParameters: - regionId – ID of region
- regionName – Name of region
- latLng – Latitude and longitude coordinates of the region
- population – Population of the region
- featureCode – Region’s feature code
-
public
Region
(JSONObject json)¶ Initialize instance fields and those of superclass based on provided JSON This class extracts the following fields, if they are present:
country_name
. It requires that the keyname
exist, as its value will be used as the region’s nameParameters: - json – JSON object describing the region to create
Throws: - JSONException – May be thrown in response to an invalidly formatted JSON object
-
public String
getFullName
()¶ Get a name for the region that lists all available geographic descriptor names. For example,
Washington, D.C.
would be expressed asWashington, D.C., United States
, whileSan Francisco
would be expressed asSan Francisco, California, United States
.Returns: Name of city that includes all available geographic descriptors
-
public class
User
implements Serializable¶ Represents a CultureMesh user’s public profile. Methods that require non-public data (e.g. email or password) take that information in as parameters and do not store it after the method completes.
-
public long
id
¶ The user’s unique identifier, which identifies them across all of CultureMesh and is constant. Not editable by user.
-
public
User
(long id, String firstName, String lastName, String username, String imgURL, String aboutMe, String gender)¶ Create a new object, storing the provided parameters into the related instance fields.
Parameters: - id – Uniquely identifies user across all of CultureMesh.
- firstName – User’s first name (may be pseudonymous)
- lastName – User’s last name (may be pseudonymous)
- username – The user’s “display name” that will serve as their main public identifier. Must be unique across all of CultureMesh’s users.
- imgURL – URL suffix (after
User.IMG_URL_PREFIX
to the user’s profile picture - aboutMe – Short bio describing the user
- gender – User’s self-identified gender
-
public
User
(long id, String firstName, String lastName, String username)¶ Create a new object, storing the provided parameters into the related instance fields. Intended to be used when creating accounts, as
img_url
,about_me
, andgender
are initialized to defaults as described in the constants forUser
.Parameters: - id – Uniquely identifies user across all of CultureMesh.
- firstName – User’s first name (may be pseudonymous)
- lastName – User’s last name (may be pseudonymous)
- username – The user’s “display name” that will serve as their main public identifier. Must be unique across all of CultureMesh’s users.
-
public
User
(JSONObject res)¶ Create a new user from a JSON that conforms to the following format:
{ "id": 0, "username": "string", "first_name": "string", "last_name": "string", "role": 0, "gender": "string", "about_me": "string", "img_link": "string", }
Other key-value pairs are acceptable, but will be ignored. Note that
img_link
does not include the baseUser.IMG_URL_PREFIX
. A missing, null, or emptyimg_link
is interpreted as an unset link, whichUser.CM_LOGO_URL
is used for.Parameters: - res – JSON describing the user to create
Throws: - JSONException – May be thrown in the case of an improperly structured JSON
-
public JSONObject
getPostJson
(String email, String password)¶ Create a JSON representation of the object that conforms to the following format:
{ "username": "string", "password": "string", "first_name": "string", "last_name": "string", "email": "string", "role": 0, "img_link": "string", "about_me": "string", "gender": "string" }
This is intended to be the format used by the
/user/users
POST endpoint. Note thatimg_link
does not include the baseUser.IMG_URL_PREFIX
. A missing, null, or emptyimg_link
is interpreted as an unset link, whichUser.CM_LOGO_URL
is used for.Throws: - JSONException – Unclear when this would be thrown
Returns: JSON representation of the object
-
public JSONObject
getPutJson
(String email)¶ Create a JSON representation of the object that conforms to the following format:
{ "id": 0, "username": "string", "first_name": "string", "last_name": "string", "email": "string", "role": 0, "gender": "string", "about_me": "string", "img_link": "string" }
This is intended to be the format used by the
/user/users
PUT endpoint. Note thatimg_link
does not include the baseUser.IMG_URL_PREFIX
. A missing, null, or emptyimg_link
is interpreted as an unset link, whichUser.CM_LOGO_URL
is used for.Throws: - JSONException – Unclear when this would be thrown
Returns: JSON representation of the object
Contributing¶
Thank you for your interest in contributing to CultureMesh Android! Here are a few steps to get you up and running:
Follow the instructions in Documentation for CultureMesh Android to get set up with the code base and Android Studio.
Open an issue on GitHub describing the changes you’d like to make. This is important beacuse your idea might already be in development or might not match the direction we are planning to take the app in. Reaching out to describe your proposal first will help avoid unnecessary work. You should also offer to work on it so people know not to do it themselves.
If your idea is accepted, start working on your idea! You might need to ask for suggestions or discuss implementation details in the issue first.
If you don’t have commit access, you’ll need to fork the repository and then clone your copy instead of the main fork.
Create a new branch for your changes:
$ git checkout -b your_branch_name
Make your changes. Please divide up your work into chunks, each of which could be un-done without breaking the app’s functionality. Make each chunk a commit. Please include comments and documentation updates as needed in your changes, preferably in the commit which necessitated them. The commit message should follow the below style (inspired by Pro-Git, page 127):
Summary on one line and under 70 characters After a blank line, you can have paragraphs as needed to more fully detail your changes. Wrap them at ~72 lines (no more than 80) for people viewing it from a command line interface. Separate paragraphs with a single line. - For bullet points, use hyphens or asterisks - You don't need a blank line between bullet points, but you should indent multiple lines to create a block of text. In your message, describe both what you changed at a high level and, more importantly, why you changed it. The rationale is important to include because it might not be clear from your code changes alone.
Push your changes:
$ git push --set-upstream origin your_branch_name
Create a pull request describing your changes and why they were made. Use the
develop
branch as the base for your pull request.Before your pull request can be accepted, it must be reviewed. Your reviewer may suggest changes, which you should then make or explain why they aren’t needed. This is a way to create dialogue about changes, which generally enhances code quality.
Once your pull request is accepted, you can delete your branch.
Warning
There are currently no automated tests for this project. Unfortunately, this means you will have to test manually to ensure your changes don’t break anything.
Getting Started¶
Getting the Latest Code¶
Clone the GitHub repository to your local machine:
$ git clone https://github.com/DrewGregory/CultureMeshAndroid
Switch to your desired branch. This will probably be either
master
, which holds the most recent release, ordevelop
, which holds the current development version. For example:$ git checkout master
Missing Information¶
For security reasons, some information is missing from the code repository:
CultureMesh API Key: Stored in
Credentials
. TheCredentials.java
file must be created with the key in a public fieldAPIKey
.Fabric API Key and Secret: Stored in
app/fabric.properties
. See template below for the structure:apiSecret=<API Secret> apiKey=<API Key>
Fill in
<API Secret>
and<API Key>
with the appropriate values.
Running the App¶
Open the root of the repository in
Android Studio. Let
Android Studio index the repository, and let Gradle install dependencies.
Then run the app by clicking the play
button in the upper right. You may have to disable Instant Run
in order to successfully use Fabric
with the API key in
app/fabric.properties
.