restafari


Source link: https://github.com/SpartanJ/restafari

restafari

restafari is an android library mostly oriented to facilitate REST API calls to a server and storing the server API response to a local SQLite database.

It's designed to be a robust library to handle all the cycle of an REST API call. It's not supposed to be a fast solution for small projects, it's intended to be used in large projects with many REST API endpoints. It works on top of Volley and Gson libraries and supports some not so very common features as cookies and proxied requests.

Getting started

Dependency

dependencies {

  compile 'com.ensoft-dev.restafari:restafari:0.2.+' 
}
 

Android Manifest

<uses-permission android:name="android.permission.INTERNET"/>

Learn by example

Creating the application DatabaseProvider

The database data is provided by a special ContentProvider supplied by the application called the DatabaseProvider. This will be the standard interface to communicate with the SQLite database. And for this we are going to create an extended DatabaseProvider from the one provided by the library. The reason for this is that we need to have a unique authority for our ContentProvider. We could simply use the one provided by the library but it could conflict with other app using the same library, so we are going to avoid it by doing the things right from the beginning.

A simple DatabaseProvider will look always look something like:

package com.ensoft.restafari_app.example;  public class DatabaseProvider extends com.ensoft.restafari.database.DatabaseProvider {
  public DatabaseProvider()  {

super( DatabaseProvider.class.getCanonicalName() );
  
}
 
}

Now we just need to add our provider to the AndroidManifest.xml.

  <provider
 android:name="com.ensoft.restafari_app.example.DatabaseProvider"
 android:authorities="com.ensoft.restafari_app.example.DatabaseProvider"
 android:exported="false"
 android:syncable="true"/>

This should be located inside the application element. android:name corresponds to the class path, and usually android:authorities should be the same ( it's not required by this is the normal way to do it ).

Initializing the library

The RequestService class is class that will handle all the HTTP requests, and just needs a contexts to be initialized.

The DatabaseService only needs to be initialized in the case that the Database features are intended to be used. It requires a TableCollection with all the table objects that the application will use during the execution and must be initialized on the attachBaseContext call ( because it must be initialized before the ContentProvider ).

package com.ensoft.restafari_app.example;  import android.app.Application; import android.content.Context;  import com.ensoft.restafari.database.DatabaseService; import com.ensoft.restafari.database.TableCollection; import com.ensoft.restafari.network.service.RequestService;  public class App extends Application {
  @Override  public void onCreate()  {

super.onCreate();

 RequestService.init( this );
  
}

@Override  protected void attachBaseContext(Context base)  {

super.attachBaseContext( base );

 TableCollection tableCollection = new TableCollection( "ipdb", 1 );

tableCollection.add( new IpTable() );

 DatabaseService.init( this, tableCollection );
  
}
 
}

Creating the table database model and response model

The model must extend from the DatabaseModel class, this class will handle the representation of the model as a table in the database.

Every table field is indicated with the annotation @DbField taking the field name from the anottation @SerializedName, and the table primary key should be explicited with @DbPrimaryKey ( the PK should be any integer type ). The primary key value should be the id of the object provided by the server. In this case we don't have a primary key so that field it's not declared. @SerializedName is also used to convert the json object from the rest api call response to a java object.

package com.ensoft.restafari_app.example;  import com.ensoft.restafari.database.DatabaseModel; import com.ensoft.restafari.database.annotations.DbField; import com.ensoft.restafari.database.annotations.DbPrimaryKey; import com.google.gson.annotations.SerializedName;  public class IpModel extends DatabaseModel {
  @SerializedName( "ip" )  @DbField  public String ip;
@SerializedName( "timestamp" )  @DbField  public long timestamp;
@SerializedName( "timestampStr" )  @DbField  public String timestampStr; 
}

Creating the table object to manage the database model

The table object is just a helper class to connect the model to the database. Extends from DatabaseTableModel indicating the database model that represents ( in this case the IpModel ). It will handle the queries, inserts, updates and deletes of the object in the database table.

package com.ensoft.restafari_app.example;  import android.content.CursorLoader;  import com.ensoft.restafari.database.DatabaseTableModel;  public class IpTable extends DatabaseTableModel<IpModel> {
  public IpTable()  {

super( IpModel.class );
  
}

// Get the IPs from the database table!  public CursorLoader getIps()  {

return new CursorLoader( getContext(), getContentUri(), tableColumns.getAll(), null, null, "timestamp DESC" );
  
}
 
}

The request object

Now that we have the model and the table we want to make a request to the server so we can fill our database with awesome data.

All the requests will have 4 parameters: the requests parameters, the requests headers, the response success listener and the response error listener.

Since the request is created with reflection the constructor must be the same for all the requests.

The library provides a variety of base kind of requests depending on the response format expected:

  • BaseJsonRequest for JSONObject responses
  • BaseJsonArrayRequest for JSONObject arrays responses.
  • BaseStringRequest for simple string responses ( not expected to be used for the normal library use )

It also supports Multipart requests for file uploading, the base classes available are:

  • BaseMultipartJsonRequest with a JSONObject response
  • BaseMultipartJsonArrayRequest with a JSONObject arrays response
  • BaseMultipartRequest for simple string responses

The parameters can be easily created with the ParametersJSONObject helper class.

The request also provides the endpoint and the request type.

package com.ensoft.restafari_app.example;  import com.android.volley.Response; import com.ensoft.restafari.network.rest.request.BaseJsonRequest;  import org.json.JSONObject;  import java.util.Map;  // The request structure public class IpRequest extends BaseJsonRequest {
  public IpRequest( JSONObject parameters, Map<String, String> headers, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener )  {

super( Method.GET, "https://ip.ensoft-dev.com/?f=json", parameters, headers, listener, errorListener );
  
}
 
}

The response processor

The response processor ( ResponseProcessor ) is the class that handles the request response from the server. And also can optionally handle the request response errors.

The ResponseProcessor should expect as a response the same model object type that the request made, in this case is IpModel. And usually you'll want to add / update / delete that object from your database table as in this case is showed. So we just instantiate our table and insert the response object to it.

package com.ensoft.restafari_app.example;  import android.content.Context;  import com.ensoft.restafari.network.processor.ResponseProcessor; import com.ensoft.restafari.network.rest.request.RequestConfiguration;  import java.text.SimpleDateFormat; import java.util.Date;  // The response processor, it runs in the background, this should be separated from the UI, this stores the result public class IpResponseProcessor extends ResponseProcessor<IpModel> {
  @Override  public void handleResponse( Context context, RequestConfiguration request, IpModel response )  {

// We can also fill some data from the client side, it's not necessary to get all the object data from the server.
response.timestamp = System.currentTimeMillis() / 1000L;
response.timestampStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format( new Date( response.timestamp * 1000L ) );

 // Saves the response object to the internal database

// This is the same as doing "new IpTable().insertOrUpdate( response );
"
response.save();
  
}

 @Override  public void handleError( Context context, RequestConfiguration request, int errorCode, String errorMessage )  {

// Do whatever you want with this  
}
 
}

How do i make the request?

We have everything ready to make a request, process it and save it to our database. Now we just need to create the request.

The RequestConfiguration class indicates to the request service who are the classes that will handle the whole process. And will return a request id that will be used later if we need to get notifications

long requestId = RequestService.getInstance().addRequest( new RequestConfiguration( IpRequest.class, IpResponseProcessor.class, IpModel.class ) );

But... how do i get the data from the database?

You will just use CursorLoader s. Any table data change will be notified by the cursor loader.

But... how? Show me please!

No problem!

I'll show you the full example with a couple of new things too ( see the comments in the code ).

package com.ensoft.restafari_app.example;  import android.app.LoaderManager; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Toast;  import com.ensoft.restafari_app.R;  import com.ensoft.restafari.network.rest.request.RequestConfiguration; import com.ensoft.restafari.network.service.RequestService; import com.ensoft.restafari.ui.view.RequestResponseActivity;  public class IpHistoryActivity extends RequestResponseActivity implements LoaderManager.LoaderCallbacks<Cursor> {
  public static final int IPS_LOADER = 1;  private long requestId;  private SimpleCursorAdapter ipsAdapter;
@Override  protected void onCreate( Bundle savedInstanceState )  {

super.onCreate( savedInstanceState );

setContentView( R.layout.activity_test );

 // get your list view ( or whatever component you wan't to use ) and set a cursor adapter to feed your list view with data
ListView ipListView = (ListView)findViewById( R.id.ipListView );

 ipsAdapter = new SimpleCursorAdapter( this,

 android.R.layout.simple_list_item_2,

 null,

 new String[] {
 "ip", "timestampStr" 
}
,

 new int [] {
 android.R.id.text1, android.R.id.text2 
}
,

 SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER
);

 ipListView.setAdapter( ipsAdapter );

 // Creates the request and add it to the request queue
requestId = RequestService.getInstance().addRequest( new RequestConfiguration( IpRequest.class, IpResponseProcessor.class, IpModel.class ) );

 // If you wan't to get a notification in the activty when the request is done ( succcesfully or not )
// you can use the `RequestReceiverService` that will handle that notifications for you. Remember to extend from a `RequestResponseActivity` activity ( you also have the Fragment equivalent `RequestResponseFragment` ).
// Add your request to the listener. 
// You'll always receive the request response, but you'll receive always when the activity is active, 
// so, if a response was received when the activity was paused, it'll be received next time the activity is resumed.
getRequestReceiverService().addRequest( requestId );

 // Init the loader manager that will handle the database queries.
getLoaderManager().initLoader( IPS_LOADER, null, this );
  
}

@Override  public void onRequestSuccess( long requestId )  {

if ( requestId == this.requestId )
{

 // Do whatever you wan't with the request response notification
 Toast.makeText( IpHistoryActivity.this, "New IP received", Toast.LENGTH_SHORT ).show();

}
  
}

@Override  public void onRequestError( long requestId, int resultCode, String resultMsg )  {

if ( requestId == this.requestId )
{

 // Do whatever you wan't with the request response notification
 Toast.makeText( IpHistoryActivity.this, "Error: " + resultCode + " Msg: " + resultMsg, Toast.LENGTH_SHORT ).show();

}
  
}

@Override  public Loader<Cursor> onCreateLoader( int id, Bundle args )  {

if ( IPS_LOADER == id )
{

 // Start loading the IPs in the table database
 return new IpTable().getIps();

}

 return null;  
}

@Override  public void onLoadFinished( Loader<Cursor> loader, Cursor data )  {

if ( loader.getId() == IPS_LOADER )
{

 // Assign the cursor to the adapter
 ipsAdapter.changeCursor( data );

}
  
}

@Override  public void onLoaderReset( Loader<Cursor> loader )  {
  
}
 
}

But... that looks overly complicated!

Well... you're somewhat right. But this is intended to be used in cases when you have a lot of interaction between the server responses and your local database. It will keep your code clean and simple.

The library also provides ways to make just simple requests without this many steps, and many other features not mentioned here. Feel free to look at the code or ask me.

License

The MIT License (MIT)  Copyright (c) 2016 Martín Lucas Golini
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 

Resources

A sweet, small set of Kotlin functions to reduce your android boilerplate code.

A simple android view for numeric progress selection.

Page indicators for use with ViewPagers.

The EasyBluetooth library allows the fast creation of Bluetooth connections between devices.

Chain of Command with background foreground options. Chains can be pre-constructed, and reused any number of times. Individual commands can be written as lambdas, or as classes.

Binds views and resources easily. Really easily. Everywhere.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes