Skip to content

Instantly share code, notes, and snippets.

@sheerazam
Created April 11, 2016 08:55
Show Gist options
  • Save sheerazam/2d2690955276b401da78fcce6547b5c7 to your computer and use it in GitHub Desktop.
Save sheerazam/2d2690955276b401da78fcce6547b5c7 to your computer and use it in GitHub Desktop.
Connect Database and Server
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<provider
android:name=".forsale.db.SalesProvider"
android:authorities="durar.durtgulfbeachrealestatecompany"
android:enabled="true"
android:exported="true"
android:syncable="true" />
add the following line to build.gradle
compile 'com.google.code.gson:gson:2.3.1'
public class CallAPI extends AsyncTask<String, String, Integer> {
@Override
protected Integer doInBackground(String... params) {
// insert english
InputStream source = retrieveStream(LINK_EN);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
List<ForSale> sales = gson.fromJson(reader, new TypeToken<List<ForSale>>(){}.getType());
insertItems(DBForSale.CONTENT_URI, sales);
source = retrieveStream(LINK_AR);
gson = new Gson();
reader = new InputStreamReader(source);
sales = gson.fromJson(reader, new TypeToken<List<ForSale>>(){}.getType());
insertItems(DBForSale.CONTENT_URI_AR, sales);
return 0;
}
private void insertItems(Uri contentUri, List<ForSale> items){
//check if shared prefs is entered...
SharedPrefsHandler sharedPrefs = new SharedPrefsHandler(ForSaleActivity.this);
// if( sharedPrefs.getPrefrences(SharedPrefsHandler.FOR_SALE_SAVED, "").length() < 0 ){
Log.d( TAG, " Item Sizes: " + items.size() );
for ( int i = 0; i < items.size(); i++ ) {
ContentValues values = new ContentValues();
values.put(DBForSale.Columns._ID, items.get(i).formId );
values.put(DBForSale.Columns.NAME, items.get(i).name );
values.put(DBForSale.Columns.PHONE_NUMBER, items.get(i).phoneNumber );
values.put(DBForSale.Columns.EMAIL, items.get(i).email );
values.put(DBForSale.Columns.BUILDING_TYPE, items.get(i).buildingType );
values.put(DBForSale.Columns.LOCATION, items.get(i).location );
values.put(DBForSale.Columns.AREA, items.get(i).area );
values.put(DBForSale.Columns.AMOUNT, items.get(i).amount );
values.put(DBForSale.Columns.ALMOOQA, items.get(i).almooqa );
values.put(DBForSale.Columns.IMAGE_NAME, items.get(i).img_name );
values.put(DBForSale.Columns.FORM_TYPE, items.get(i).formType );
values.put(DBForSale.Columns.LANG_MODE, items.get(i).langMode );
values.put(DBForSale.Columns.NOTES, items.get(i).notes );
values.put(DBForSale.Columns.STATUS, items.get(i).status );
values.put(DBForSale.Columns.SUBMIT_DATE, items.get(i).submitDate );
getContentResolver().insert(contentUri, values);
sharedPrefs.setPrefrences(SharedPrefsHandler.FOR_SALE_SAVED, "Saved");
}
// }
}
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
}
public class DB {
public static final String AUTHORITY = "durar.durtgulfbeachrealestatecompany";
public static final String DB_NAME = "durar.db";
public static final int DB_VERSION = 2;
}
/** Just constants related to For Sale Provider and its database. */
public final class DBForSale {
private DBForSale() {}
public static final String TABLE = "forsale";
public static final String TABLE_AR = "forsale_ar";
// public static final String SORT_ORDER = Columns.APPOINTMENT_DATE + " asc, " + SrxDBPatients.Columns.NAME + " asc";
public static final Uri CONTENT_URI_AR = Uri.parse("content://" + DB.AUTHORITY + "/" + TABLE_AR);
public static final Uri CONTENT_URI = Uri.parse("content://" + DB.AUTHORITY + "/" + TABLE);
public static final class Columns implements BaseColumns {
private Columns() {}
public static final String NAME = "name";
public static final String PHONE_NUMBER = "phone_number";
public static final String EMAIL = "email";
public static final String BUILDING_TYPE = "building_type";
public static final String LOCATION = "location";
public static final String AREA = "area";
public static final String AMOUNT = "amount";
public static final String ALMOOQA = "almooqa";
public static final String IMAGE_NAME = "img_name";
public static final String FORM_TYPE = "form_type";
public static final String LANG_MODE = "lang_mode";
public static final String NOTES = "notes";
public static final String STATUS = "status";
public static final String SUBMIT_DATE = "submit_date";
}
}
/** Database helper class for database creation, update and deletion,
* this class is basic class runs the SQLite Queries for creating tables in the database,
* this class is only used in SrxProvider class*/
public class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DB.DB_NAME, null, DB.DB_VERSION);
}
/** Called only once to create the database first time. */
@Override
public void onCreate(final SQLiteDatabase db) {
String sql;
// For Sale
sql = createTableForSale();
db.execSQL(sql);
sql = createTableForSaleAR();
db.execSQL(sql);
Log.d("DbHelper", "OnCreate() Called...");
}
/** Called every time oldVersion != newVersion. */
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Typically you do ALTER TABLE ..., but we don't have previous userbase
db.execSQL("drop table if exists " + DBForSale.TABLE);
this.onCreate(db);
}
private String createTableForSale() {
String sql = String.format(
"CREATE TABLE \"forsale\" (\"_id\" VARCHAR PRIMARY KEY NOT NULL UNIQUE , \"name\" VARCHAR, \"phone_number\" VARCHAR, \"email\" VARCHAR, \"building_type\" VARCHAR, \"location\" VARCHAR, \"area\" VARCHAR, \"amount\" VARCHAR, \"almooqa\" VARCHAR, \"img_name\" VARCHAR, \"form_type\" VARCHAR, \"lang_mode\" VARCHAR, \"notes\" VARCHAR, \"status\" VARCHAR, \"submit_date\" VARCHAR NOT NULL )"
);
Log.v("DbHelper", "SQL: " + sql);
return sql;
}
private String createTableForSaleAR() {
String sql = String.format(
"CREATE TABLE \"forsale_ar\" (\"_id\" VARCHAR PRIMARY KEY NOT NULL UNIQUE , \"name\" VARCHAR, \"phone_number\" VARCHAR, \"email\" VARCHAR, \"building_type\" VARCHAR, \"location\" VARCHAR, \"area\" VARCHAR, \"amount\" VARCHAR, \"almooqa\" VARCHAR, \"img_name\" VARCHAR, \"form_type\" VARCHAR, \"lang_mode\" VARCHAR, \"notes\" VARCHAR, \"status\" VARCHAR, \"submit_date\" VARCHAR NOT NULL )"
);
Log.v("DbHelper", "SQL: " + sql);
return sql;
}
}
/**
* Created by sheerazam on 13/04/15.
*/
public class ForSale {
@SerializedName("form_id")
public String formId;
@SerializedName("name")
public String name;
@SerializedName("phone_number")
public String phoneNumber;
@SerializedName("email")
public String email;
@SerializedName("building_type")
public String buildingType;
@SerializedName("location")
public String location;
@SerializedName("area")
public String area;
@SerializedName("amount")
public String amount;
@SerializedName("almooqa")
public String almooqa;
@SerializedName("img_name")
public String img_name;
@SerializedName("form_type")
public String formType;
@SerializedName("lang_mode")
public String langMode;
@SerializedName("notes")
public String notes;
@SerializedName("status")
public String status;
@SerializedName("submit_date")
public String submitDate;
}
//Add loader manager for database access....
public class ForSaleActivity extends ActionBarActivity implements ForSaleView, LoaderManager.LoaderCallbacks<Cursor> {
String [] PROJECTION = new String [] {
DBForSale.Columns._ID,
DBForSale.Columns.ALMOOQA,
DBForSale.Columns.AMOUNT,
DBForSale.Columns.AREA,
DBForSale.Columns.BUILDING_TYPE,
DBForSale.Columns.EMAIL,
DBForSale.Columns.FORM_TYPE,
DBForSale.Columns.IMAGE_NAME,
DBForSale.Columns.LANG_MODE,
DBForSale.Columns.LOCATION,
DBForSale.Columns.NAME,
DBForSale.Columns.NOTES,
DBForSale.Columns.PHONE_NUMBER,
DBForSale.Columns.STATUS,
DBForSale.Columns.SUBMIT_DATE
};
@Override
protected void onCreate(Bundle savedInstanceState) {
//call the api if network is available
if(isNetworkAvailable()){
CallAPI callAPI = new CallAPI();
callAPI.execute();
}
int list_layout = R.layout.for_sale_list_item;
//create new cursor adapter...
adapter = new ForSaleCursorAdapter(this, null, list_layout);
//initialize the loader
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String select = null;
Uri content_uri = DBForSale.CONTENT_URI;
Log.d("getLanguage():", getLanguage());
if(getLanguage().equals("ar")){
content_uri = DBForSale.CONTENT_URI_AR;
}
Log.d("Content URI", content_uri.toString());
return new CursorLoader( this, content_uri , PROJECTION, null, null, DBForSale.Columns._ID + " asc" );
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/**
* @author Sheeraz Ahmed
*
*
* This class extends Android's Content Provider class for record creation, update and deletion in database, and uses DBHelper class.
*
*/
public class SalesProvider extends ContentProvider {
private DbHelper dbHelper;
// Single
private static final int SALES = 1;
String TAG = "SrxProvider";
@Override
public boolean onCreate() {
// create new database helper to setup database
dbHelper = new DbHelper(getContext());
return true;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
long id = 0;
// TODO : use Uri Matcher
//String table = Globals.UritoTableName(uri);
String table = getTablesFromUri(uri);
Log.v(TAG, table);
try {
assert db != null;
id = db.insertWithOnConflict( table, null, values,
SQLiteDatabase.CONFLICT_IGNORE );
Log.v(TAG, "Id: " + id);
}
catch(Exception e ){
Log.e(TAG, e.toString());
}
if (id > 0) {
getContext().getContentResolver().notifyChange(uri, null);
return ContentUris.withAppendedId(uri, id);
} else {
return null;
}
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
//String table = Globals.UritoTableName(uri);
String table = getTablesFromUri(uri);
assert db != null;
int id = db.update(table, values, selection, selectionArgs);
Log.v(TAG, id + "");
if (id > 0) {
getContext().getContentResolver().notifyChange(uri, null);
return id;
} else {
return id;
}
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO : use Uri Matcher
String table = getTablesFromUri(uri);
SQLiteDatabase db = dbHelper.getWritableDatabase();
assert db != null;
int id = db.delete(table, selection, selectionArgs);
if (id > 0) {
getContext().getContentResolver().notifyChange(uri, null);
return id;
} else {
return 0;
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Log.v(TAG, uri.toString());
//Log.v(TAG, table_name );
Cursor cursor;
SQLiteQueryBuilder querybuilder = new SQLiteQueryBuilder();
querybuilder.setTables( getTablesFromUri(uri) );
Log.v(TAG, querybuilder.buildQuery(projection, selection, null, null, sortOrder, null));
assert db != null;
cursor = querybuilder.query(db, projection, selection, selectionArgs,null, null, sortOrder);
assert cursor != null;
cursor.setNotificationUri( getContext().getContentResolver(), uri);
return cursor;
}
private String getTablesFromUri(Uri uri){
String tables = null;
if( uri.toString().equals(DBForSale.CONTENT_URI.toString()) )
tables = DBForSale.TABLE;
else if( uri.toString().equals(DBForSale.CONTENT_URI_AR.toString()) )
tables = DBForSale.TABLE_AR;
return tables;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment