List of usage examples for android.database Cursor getInt
int getInt(int columnIndex);
From source file:org.noorganization.instalistsynch.controller.synch.impl.ListSynch.java
@Override public void indexLocal(int _groupId, Date _lastIndexTime) { String lastIndexTime = ISO8601Utils.format(_lastIndexTime, false, TimeZone.getTimeZone("GMT+0000"));//.concat("+0000"); boolean isLocal = false; GroupAuth groupAuth = mGroupAuthDbController.getLocalGroup(); if (groupAuth != null) { isLocal = groupAuth.getGroupId() == _groupId; }//from www .j ava 2 s . c om Cursor logCursor = mClientLogDbController.getLogsSince(lastIndexTime, mModelType); if (logCursor.getCount() == 0) { logCursor.close(); return; } try { while (logCursor.moveToNext()) { // fetch the action type int actionId = logCursor.getInt(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION)); eActionType actionType = eActionType.getTypeById(actionId); List<ModelMapping> modelMappingList = mListModelMappingController.get( ModelMapping.COLUMN.GROUP_ID + " = ? AND " + ModelMapping.COLUMN.CLIENT_SIDE_UUID + " LIKE ?", new String[] { String.valueOf(_groupId), logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)) }); ModelMapping modelMapping = modelMappingList.size() == 0 ? null : modelMappingList.get(0); switch (actionType) { case INSERT: // skip insertion because this should be decided by the user if the non local groups should have access to the category // and also skip if a mapping for this case already exists! if (!isLocal || modelMapping != null) { continue; } String clientUuid = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)); Date clientDate = ISO8601Utils.parse( logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)), new ParsePosition(0)); modelMapping = new ModelMapping(null, groupAuth.getGroupId(), null, clientUuid, new Date(Constants.INITIAL_DATE), clientDate, false); mListModelMappingController.insert(modelMapping); break; case UPDATE: if (modelMapping == null) { Log.i(TAG, "indexLocal: the model is null but shouldn't be"); continue; } String timeString = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)); clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0)); modelMapping.setLastClientChange(clientDate); mListModelMappingController.update(modelMapping); break; case DELETE: if (modelMapping == null) { Log.i(TAG, "indexLocal: the model is null but shouldn't be"); continue; } modelMapping.setDeleted(true); timeString = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)); clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0)); modelMapping.setLastClientChange(clientDate); mListModelMappingController.update(modelMapping); break; default: } } } catch (Exception e) { logCursor.close(); } }
From source file:org.noorganization.instalistsynch.controller.synch.impl.ProductSynch.java
@Override public void indexLocal(int _groupId, Date _lastIndexTime) { String lastIndexTime = ISO8601Utils.format(_lastIndexTime, false, TimeZone.getTimeZone("GMT+0000"));//.concat("+0000"); boolean isLocal = false; GroupAuth groupAuth = mGroupAuthDbController.getLocalGroup(); if (groupAuth != null) { isLocal = groupAuth.getGroupId() == _groupId; }//from ww w . j av a2s . c o m Cursor logCursor = mClientLogDbController.getLogsSince(lastIndexTime, mModelType); if (logCursor.getCount() == 0) { logCursor.close(); return; } try { while (logCursor.moveToNext()) { // fetch the action type int actionId = logCursor.getInt(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION)); eActionType actionType = eActionType.getTypeById(actionId); List<ModelMapping> modelMappingList = mProductModelMapping.get( ModelMapping.COLUMN.GROUP_ID + " = ? AND " + ModelMapping.COLUMN.CLIENT_SIDE_UUID + " LIKE ?", new String[] { String.valueOf(_groupId), logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)) }); ModelMapping modelMapping = modelMappingList.size() == 0 ? null : modelMappingList.get(0); switch (actionType) { case INSERT: // skip insertion because this should be decided by the user if the non local groups should have access to the category // and also skip if a mapping for this case already exists! if (!isLocal || modelMapping != null) { continue; } String clientUuid = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ITEM_UUID)); Date clientDate = ISO8601Utils.parse( logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)), new ParsePosition(0)); modelMapping = new ModelMapping(null, groupAuth.getGroupId(), null, clientUuid, new Date(Constants.INITIAL_DATE), clientDate, false); mProductModelMapping.insert(modelMapping); break; case UPDATE: if (modelMapping == null) { Log.i(TAG, "indexLocal: the model is null but shouldn't be"); continue; } String timeString = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)); clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0)); modelMapping.setLastClientChange(clientDate); mProductModelMapping.update(modelMapping); break; case DELETE: if (modelMapping == null) { Log.i(TAG, "indexLocal: the model is null but shouldn't be"); continue; } modelMapping.setDeleted(true); timeString = logCursor.getString(logCursor.getColumnIndex(LogInfo.COLUMN.ACTION_DATE)); clientDate = ISO8601Utils.parse(timeString, new ParsePosition(0)); modelMapping.setLastClientChange(clientDate); mProductModelMapping.update(modelMapping); break; default: } } } catch (Exception e) { logCursor.close(); } }
From source file:com.piusvelte.sonet.core.SelectFriends.java
protected void loadFriends() { mFriends.clear();/*from w w w .j a v a2 s . com*/ // SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND, Entities.ESID}, new int[]{R.id.profile, R.id.name, R.id.selected}); SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected }); setListAdapter(sa); final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Long, String, Boolean> asyncTask = new AsyncTask<Long, String, Boolean>() { @Override protected Boolean doInBackground(Long... params) { boolean loadList = false; SonetCrypto sonetCrypto = SonetCrypto.getInstance(getApplicationContext()); // load the session Cursor account = getContentResolver().query(Accounts.getContentUri(SelectFriends.this), new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE }, Accounts._ID + "=?", new String[] { Long.toString(params[0]) }, null); if (account.moveToFirst()) { mToken = sonetCrypto.Decrypt(account.getString(0)); mSecret = sonetCrypto.Decrypt(account.getString(1)); mService = account.getInt(2); } account.close(); String response; switch (mService) { case TWITTER: break; case FACEBOOK: if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet( String.format(FACEBOOK_FRIENDS, FACEBOOK_BASE_URL, Saccess_token, mToken)))) != null) { try { JSONArray friends = new JSONObject(response).getJSONArray(Sdata); for (int i = 0, l = friends.length(); i < l; i++) { JSONObject f = friends.getJSONObject(i); HashMap<String, String> newFriend = new HashMap<String, String>(); newFriend.put(Entities.ESID, f.getString(Sid)); newFriend.put(Entities.PROFILE, String.format(FACEBOOK_PICTURE, f.getString(Sid))); newFriend.put(Entities.FRIEND, f.getString(Sname)); // need to alphabetize if (mFriends.isEmpty()) mFriends.add(newFriend); else { String fullName = f.getString(Sname); int spaceIdx = fullName.lastIndexOf(" "); String newFirstName = null; String newLastName = null; if (spaceIdx == -1) newFirstName = fullName; else { newFirstName = fullName.substring(0, spaceIdx++); newLastName = fullName.substring(spaceIdx); } List<HashMap<String, String>> newFriends = new ArrayList<HashMap<String, String>>(); for (int i2 = 0, l2 = mFriends.size(); i2 < l2; i2++) { HashMap<String, String> oldFriend = mFriends.get(i2); if (newFriend == null) { newFriends.add(oldFriend); } else { fullName = oldFriend.get(Entities.FRIEND); spaceIdx = fullName.lastIndexOf(" "); String oldFirstName = null; String oldLastName = null; if (spaceIdx == -1) oldFirstName = fullName; else { oldFirstName = fullName.substring(0, spaceIdx++); oldLastName = fullName.substring(spaceIdx); } if (newFirstName == null) { newFriends.add(newFriend); newFriend = null; } else { int comparison = oldFirstName.compareToIgnoreCase(newFirstName); if (comparison == 0) { // compare firstnames if (newLastName == null) { newFriends.add(newFriend); newFriend = null; } else if (oldLastName != null) { comparison = oldLastName.compareToIgnoreCase(newLastName); if (comparison == 0) { newFriends.add(newFriend); newFriend = null; } else if (comparison > 0) { newFriends.add(newFriend); newFriend = null; } } } else if (comparison > 0) { newFriends.add(newFriend); newFriend = null; } } newFriends.add(oldFriend); } } if (newFriend != null) newFriends.add(newFriend); mFriends = newFriends; } } loadList = true; } catch (JSONException e) { Log.e(TAG, e.toString()); } } break; case MYSPACE: break; case LINKEDIN: break; case FOURSQUARE: break; case IDENTICA: break; case GOOGLEPLUS: break; case CHATTER: break; } return loadList; } @Override protected void onPostExecute(Boolean loadList) { if (loadList) { // SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND}, new int[]{R.id.profile, R.id.name}); SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected }); sa.setViewBinder(mViewBinder); setListAdapter(sa); } if (loadingDialog.isShowing()) loadingDialog.dismiss(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); loadingDialog.show(); asyncTask.execute(mAccountId); }
From source file:com.money.manager.ex.database.MmxOpenHelper.java
private void initBaseCurrency(SQLiteDatabase db) { // currencies CurrencyService currencyService = new CurrencyService(getContext()); Currency systemCurrency = currencyService.getSystemDefaultCurrency(); if (systemCurrency == null) return;// w ww. j a v a 2 s. c om InfoService infoService = new InfoService(getContext()); // todo: try query generator. // String sql = new Select() // .select() // .from(InfoRepositorySql.TABLE_NAME) // .where(Info.INFONAME + "=?", InfoKeys.BASECURRENCYID) // .toString(); Cursor currencyCursor = db.rawQuery( "SELECT * FROM " + InfoRepositorySql.TABLE_NAME + " WHERE " + Info.INFONAME + "=?", new String[] { InfoKeys.BASECURRENCYID }); if (currencyCursor == null) return; // Get id of the base currency record. int recordId = Constants.NOT_SET; boolean recordExists = currencyCursor.moveToFirst(); if (recordExists) { recordId = currencyCursor.getInt(currencyCursor.getColumnIndex(Info.INFOID)); } currencyCursor.close(); // Use the system default currency. int currencyId = currencyService.loadCurrencyIdFromSymbolRaw(db, systemCurrency.getCurrencyCode()); if (currencyId == Constants.NOT_SET) { // Use Euro by default. currencyId = 2; } UIHelper uiHelper = new UIHelper(getContext()); // Insert/update base currency record into info table. if (!recordExists) { long newId = infoService.insertRaw(db, InfoKeys.BASECURRENCYID, currencyId); if (newId <= 0) { uiHelper.showToast("error inserting base currency on init"); } } else { // Update the (by default empty) record to the default currency. long updatedRecords = infoService.updateRaw(db, recordId, InfoKeys.BASECURRENCYID, currencyId); if (updatedRecords <= 0) { uiHelper.showToast("error updating base currency on init"); } } // Can't use provider here as the database is not ready. // int currencyId = currencyService.loadCurrencyIdFromSymbol(systemCurrency.getCurrencyCode()); // String baseCurrencyId = infoService.getInfoValue(InfoService.BASECURRENCYID); // if (!StringUtils.isEmpty(baseCurrencyId)) return; // infoService.setInfoValue(InfoService.BASECURRENCYID, Integer.toString(currencyId)); }
From source file:com.ichi2.anki.stats.OverviewStatsBuilder.java
private List<int[]> _due(Integer start, Integer end, int chunk) { String lim = ""; if (start != null) { lim += String.format(Locale.US, " and due-%d >= %d", mCol.getSched().getToday(), start); }//from ww w . ja va 2 s.c o m if (end != null) { lim += String.format(Locale.US, " and day < %d", end); } List<int[]> d = new ArrayList<>(); Cursor cur = null; try { String query; query = String.format(Locale.US, "select (due-%d)/%d as day,\n" + "sum(case when ivl < 21 then 1 else 0 end), -- yng\n" + "sum(case when ivl >= 21 then 1 else 0 end) -- mtr\n" + "from cards\n" + "where did in %s and queue in (2,3)\n" + "%s\n" + "group by day order by day", mCol.getSched().getToday(), chunk, _limit(), lim); cur = mCol.getDb().getDatabase().rawQuery(query, null); while (cur.moveToNext()) { d.add(new int[] { cur.getInt(0), cur.getInt(1), cur.getInt(2) }); } } finally { if (cur != null && !cur.isClosed()) { cur.close(); } } return d; }
From source file:com.example.android.basicsyncadapter.SyncAdapter.java
/** * Read XML from an input stream, storing it into the content provider. * * <p>This is where incoming data is persisted, committing the results of a sync. In order to * minimize (expensive) disk operations, we compare incoming data with what's already in our * database, and compute a merge. Only changes (insert/update/delete) will result in a database * write./*from w ww. j a v a 2 s. c om*/ * * <p>As an additional optimization, we use a batch operation to perform all database writes at * once. * * <p>Merge strategy: * 1. Get cursor to all items in feed<br/> * 2. For each item, check if it's in the incoming data.<br/> * a. YES: Remove from "incoming" list. Check if data has mutated, if so, perform * database UPDATE.<br/> * b. NO: Schedule DELETE from database.<br/> * (At this point, incoming database only contains missing items.)<br/> * 3. For any items remaining in incoming list, ADD to database. */ public void updateLocalFeedData(final InputStream stream, final SyncResult syncResult) throws IOException, XmlPullParserException, RemoteException, OperationApplicationException, ParseException { //final FeedParser feedParser = new FeedParser(); final CAPFeedParser feedParser = new CAPFeedParser(); final ContentResolver contentResolver = getContext().getContentResolver(); //Log.i(TAG, "Parsing stream as Atom feed"); final List<CAPFeedParser.Entry> entries = feedParser.parse(stream); Log.i(TAG, "Parsing complete. Found " + entries.size() + " entries"); ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(); // Build hash table of incoming entries HashMap<String, CAPFeedParser.Entry> entryMap = new HashMap<String, CAPFeedParser.Entry>(); for (CAPFeedParser.Entry e : entries) { entryMap.put(e.id, e); } // Get list of all items //Log.i(TAG, "Fetching local entries for merge"); Uri uri = FeedContract.Entry.CONTENT_URI; // Get all entries Cursor c = contentResolver.query(uri, PROJECTION, null, null, null); assert c != null; //Log.i(TAG, "Found " + c.getCount() + " local entries. Computing merge solution..."); // Find stale data int id; String entryId; String title; String description; String headline; String url; String areas; String issued; while (c.moveToNext()) { syncResult.stats.numEntries++; id = c.getInt(COLUMN_ID); entryId = c.getString(COLUMN_ENTRY_ID); title = c.getString(COLUMN_TITLE); description = c.getString(COLUMN_DESCRIPTION); headline = c.getString(COLUMN_HEADLINE); areas = c.getString(COLUMN_AREAS); url = c.getString(COLUMN_LINK); issued = c.getString(COLUMN_ISSUED); CAPFeedParser.Entry match = entryMap.get(entryId); if (match != null) { // Entry exists. Remove from entry map to prevent insert later. entryMap.remove(entryId); // Check to see if the entry needs to be updated Uri existingUri = FeedContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id)) .build(); if ((match.title != null && !match.title.equals(title)) || (match.link != null && !match.link.equals(url)) || (match.issued != issued)) { // Update existing record //Log.i(TAG, "Scheduling update: " + existingUri); batch.add(ContentProviderOperation.newUpdate(existingUri) .withValue(FeedContract.Entry.COLUMN_NAME_TITLE, title) .withValue(FeedContract.Entry.COLUMN_NAME_DESCRIPTION, description) .withValue(FeedContract.Entry.COLUMN_NAME_HEADLINE, headline) .withValue(FeedContract.Entry.COLUMN_NAME_ISSUED, issued) .withValue(FeedContract.Entry.COLUMN_NAME_LINK, url) .withValue(FeedContract.Entry.COLUMN_NAME_AREAS, areas).build()); syncResult.stats.numUpdates++; } else { //Log.i(TAG, "No action: " + existingUri); } } else { // Entry doesn't exist. Remove it from the database. Uri deleteUri = FeedContract.Entry.CONTENT_URI.buildUpon().appendPath(Integer.toString(id)).build(); //Log.i(TAG, "Scheduling delete: " + deleteUri); batch.add(ContentProviderOperation.newDelete(deleteUri).build()); syncResult.stats.numDeletes++; } } c.close(); // Add new items for (CAPFeedParser.Entry e : entryMap.values()) { //Log.i(TAG, "Scheduling insert: entry_id=" + e.id); batch.add(ContentProviderOperation.newInsert(FeedContract.Entry.CONTENT_URI) .withValue(FeedContract.Entry.COLUMN_NAME_ENTRY_ID, e.id) .withValue(FeedContract.Entry.COLUMN_NAME_TITLE, e.title) .withValue(FeedContract.Entry.COLUMN_NAME_DESCRIPTION, e.description) .withValue(FeedContract.Entry.COLUMN_NAME_HEADLINE, e.headline) .withValue(FeedContract.Entry.COLUMN_NAME_ISSUED, e.issued) .withValue(FeedContract.Entry.COLUMN_NAME_LINK, e.link) .withValue(FeedContract.Entry.COLUMN_NAME_AREAS, e.areas).build()); syncResult.stats.numInserts++; } //Log.i(TAG, "Merge solution ready. Applying batch update"); mContentResolver.applyBatch(FeedContract.CONTENT_AUTHORITY, batch); mContentResolver.notifyChange(FeedContract.Entry.CONTENT_URI, // URI where data was modified null, // No local observer false); // IMPORTANT: Do not sync to network // This sample doesn't support uploads, but if *your* code does, make sure you set // syncToNetwork=false in the line above to prevent duplicate syncs. }
From source file:com.openerp.addons.messages.MessageComposeActivty.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_message_compose); scope = new AppScope((MainActivity) MainActivity.context); getActionBar().setHomeButtonEnabled(true); getActionBar().setDisplayHomeAsUpEnabled(true); Intent replyIntent = getIntent();/*from w ww . java 2 s.com*/ receipients_view = (TagsView) findViewById(R.id.receipients_view); partner_adapter = new ReceipientsTagsCustomAdapter(this, R.layout.message_receipient_item_layout, parters); receipients_view.setAdapter(partner_adapter); /* tags component */ if (replyIntent.hasExtra("send_reply")) { is_reply = true; } else { parters.addAll(getAllPartners()); } receipients_view.setPrefix("To: "); receipients_view.allowDuplicates(false); receipients_view.setTokenListener(this); if (is_reply) { message_id = replyIntent.getExtras().getInt("message_id"); MessageDBHelper msgDb = new MessageDBHelper(this); parent_row = ((List<HashMap<String, Object>>) msgDb.search(msgDb, new String[] { "id = ?" }, new String[] { message_id + "" }).get("records")).get(0); getActionBar().setTitle("?"); EditText edtSubject = (EditText) findViewById(R.id.edtMessageSubject); edtSubject.setText("?: " + parent_row.get("subject").toString()); JSONArray partner_ids = new JSONArray(); try { List<TagsItems> partners = getPartnersOfMessage(message_id + ""); for (TagsItems item : partners) { selectedPartners.put("key_" + item.getId(), item); partner_ids.put(item.getId()); receipients_view.addObject(item); findViewById(R.id.edtMessageBody).requestFocus(); } parent_row.put("partners", partner_ids); } catch (Exception e) { e.printStackTrace(); } } else { getActionBar().setTitle("??"); if (getIntent().getData() != null) { Cursor cursor = managedQuery(getIntent().getData(), null, null, null, null); if (cursor.moveToNext()) { int partner_id = cursor.getInt(cursor.getColumnIndex("data2")); List<TagsItems> partners = getPartnersByIds(Arrays.asList(new Integer[] { partner_id })); for (TagsItems item : partners) { selectedPartners.put("key_" + item.getId(), item); receipients_view.addObject(item); findViewById(R.id.edtMessageSubject).requestFocus(); } } } } lstAttachments = (ListView) findViewById(R.id.lstAttachments); String[] from = new String[] { "name" }; int[] to = new int[] { R.id.txvFileName }; lstAttachmentAdapter = new OEListViewAdapter(MainActivity.context, R.layout.message_attachment_listview_item, attachments, from, to, null); lstAttachments.setAdapter(lstAttachmentAdapter); lstAttachmentAdapter.setItemClickListener(R.id.imgBtnRemoveAttachment, new ControlClickEventListener() { @Override public OEListViewRows controlClicked(int position, OEListViewRows row, View view) { file_uris.remove(position); attachments.remove(position); lstAttachmentAdapter.refresh(attachments); return null; } }); Res_PartnerDBHelper partners = new Res_PartnerDBHelper(this); HashMap<String, Object> data = partners.search(partners); if ((Integer) data.get("total") > 0) { for (HashMap<String, Object> row : (List<HashMap<String, Object>>) data.get("records")) { OEListViewRows newRow = new OEListViewRows(Integer.parseInt(row.get("id").toString()), row); partners_list.add(newRow); } } handleIntentFilter(getIntent()); }
From source file:at.bitfire.davdroid.mirakel.resource.LocalCalendar.java
void populateReminders(Event e) throws RemoteException { // reminders//ww w. ja v a 2s. c o m Uri remindersUri = Reminders.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build(); @Cleanup Cursor c = providerClient.query(remindersUri, new String[] { /* 0 */ Reminders.MINUTES, Reminders.METHOD }, Reminders.EVENT_ID + "=?", new String[] { String.valueOf(e.getLocalID()) }, null); while (c != null && c.moveToNext()) { VAlarm alarm = new VAlarm(new Dur(0, 0, -c.getInt(0), 0)); PropertyList props = alarm.getProperties(); switch (c.getInt(1)) { /*case Reminders.METHOD_EMAIL: props.add(Action.EMAIL); break;*/ default: props.add(Action.DISPLAY); props.add(new Description(e.getSummary())); } e.addAlarm(alarm); } }
From source file:com.example.android.ennis.barrett.popularmovies.asynchronous.TMDbSyncUtil.java
/** * Parses and stores the JSON data in the TMDbContentProvider * @param dataJSON The JSON data from server * @param type Flag for the try of movie to fetch. Should match flag used in fetchMovies * @throws JSONException//from w w w .j a v a 2 s. c o m */ private static int[] storeJsonMovies(String dataJSON, int type, Context context) throws JSONException { //TODO use ContentProviderClient instead of ContentResolver try { JSONObject moviesJSON = new JSONObject(dataJSON); JSONArray results = moviesJSON.getJSONArray("results"); final int resultLength = results.length(); ContentValues[] contentValues = new ContentValues[resultLength]; int[] ids = new int[resultLength]; int isPopular; int isTopRated; int isFavorite; switch (type) { case MOVIES_POPULAR: isPopular = 1; isTopRated = 0; break; case MOVIES_TOP_RATED: isPopular = 0; isTopRated = 1; break; default: isPopular = 0; isTopRated = 0; } Cursor cursor = getFavoriteIds(context); ContentResolver contentResolver = context.getContentResolver(); for (int i = 0; i < resultLength; i++) { JSONObject movie = results.getJSONObject(i); contentValues[i] = new ContentValues(); contentValues[i].put(TMDbContract.Movies.ORIGINAL_TITLE, movie.getString(TMDbContract.Movies.ORIGINAL_TITLE)); contentValues[i].put(TMDbContract.Movies.OVERVIEW, movie.getString(TMDbContract.Movies.OVERVIEW)); contentValues[i].put(TMDbContract.Movies.POSTER, movie.getString(TMDbContract.Movies.POSTER)); contentValues[i].put(TMDbContract.Movies.RELEASE_DATE, movie.getString(TMDbContract.Movies.RELEASE_DATE)); contentValues[i].put(TMDbContract.Movies.POPULARITY, movie.getDouble(TMDbContract.Movies.POPULARITY)); contentValues[i].put(TMDbContract.Movies.VOTE_AVERAGE, movie.getDouble(TMDbContract.Movies.VOTE_AVERAGE)); int moveId = movie.getInt(TMDbContract.Movies.MOVIE_ID); contentValues[i].put(TMDbContract.Movies.MOVIE_ID, moveId); cursor.moveToPosition(-1); while (cursor.moveToNext()) { int favoriteId = cursor.getInt(cursor.getColumnIndex(TMDbContract.Movies.MOVIE_ID)); if (favoriteId == moveId) { deleteFavorite(context, moveId); isFavorite = 1; contentValues[i].put(TMDbContract.Movies.IS_FAVORITE, isFavorite); break; } } //TODO read up on how to have the col initialized to 0 by defualt contentValues[i].put(TMDbContract.Movies.IS_POPULAR, isPopular); contentValues[i].put(TMDbContract.Movies.IS_TOP_RATED, isTopRated); ids[i] = movie.getInt(TMDbContract.Movies.MOVIE_ID); } int numInserted = contentResolver.bulkInsert(TMDbContract.Movies.URI, contentValues); if (numInserted != resultLength) { Log.e(TAG, "Not all of the result were inserted.\n Amount inserted: " + numInserted + "\nAmount from server: " + resultLength); } return ids; } catch (JSONException e) { Log.d(TAG, e.getMessage(), e); e.printStackTrace(); return null; } }
From source file:com.shafiq.myfeedle.core.SelectFriends.java
protected void loadFriends() { mFriends.clear();//from www . j a v a 2 s .com // SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND, Entities.ESID}, new int[]{R.id.profile, R.id.name, R.id.selected}); SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected }); setListAdapter(sa); final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Long, String, Boolean> asyncTask = new AsyncTask<Long, String, Boolean>() { @Override protected Boolean doInBackground(Long... params) { boolean loadList = false; MyfeedleCrypto myfeedleCrypto = MyfeedleCrypto.getInstance(getApplicationContext()); // load the session Cursor account = getContentResolver().query(Accounts.getContentUri(SelectFriends.this), new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE }, Accounts._ID + "=?", new String[] { Long.toString(params[0]) }, null); if (account.moveToFirst()) { mToken = myfeedleCrypto.Decrypt(account.getString(0)); mSecret = myfeedleCrypto.Decrypt(account.getString(1)); mService = account.getInt(2); } account.close(); String response; switch (mService) { case TWITTER: break; case FACEBOOK: if ((response = MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet( String.format(FACEBOOK_FRIENDS, FACEBOOK_BASE_URL, Saccess_token, mToken)))) != null) { try { JSONArray friends = new JSONObject(response).getJSONArray(Sdata); for (int i = 0, l = friends.length(); i < l; i++) { JSONObject f = friends.getJSONObject(i); HashMap<String, String> newFriend = new HashMap<String, String>(); newFriend.put(Entities.ESID, f.getString(Sid)); newFriend.put(Entities.PROFILE, String.format(FACEBOOK_PICTURE, f.getString(Sid))); newFriend.put(Entities.FRIEND, f.getString(Sname)); // need to alphabetize if (mFriends.isEmpty()) mFriends.add(newFriend); else { String fullName = f.getString(Sname); int spaceIdx = fullName.lastIndexOf(" "); String newFirstName = null; String newLastName = null; if (spaceIdx == -1) newFirstName = fullName; else { newFirstName = fullName.substring(0, spaceIdx++); newLastName = fullName.substring(spaceIdx); } List<HashMap<String, String>> newFriends = new ArrayList<HashMap<String, String>>(); for (int i2 = 0, l2 = mFriends.size(); i2 < l2; i2++) { HashMap<String, String> oldFriend = mFriends.get(i2); if (newFriend == null) { newFriends.add(oldFriend); } else { fullName = oldFriend.get(Entities.FRIEND); spaceIdx = fullName.lastIndexOf(" "); String oldFirstName = null; String oldLastName = null; if (spaceIdx == -1) oldFirstName = fullName; else { oldFirstName = fullName.substring(0, spaceIdx++); oldLastName = fullName.substring(spaceIdx); } if (newFirstName == null) { newFriends.add(newFriend); newFriend = null; } else { int comparison = oldFirstName.compareToIgnoreCase(newFirstName); if (comparison == 0) { // compare firstnames if (newLastName == null) { newFriends.add(newFriend); newFriend = null; } else if (oldLastName != null) { comparison = oldLastName.compareToIgnoreCase(newLastName); if (comparison == 0) { newFriends.add(newFriend); newFriend = null; } else if (comparison > 0) { newFriends.add(newFriend); newFriend = null; } } } else if (comparison > 0) { newFriends.add(newFriend); newFriend = null; } } newFriends.add(oldFriend); } } if (newFriend != null) newFriends.add(newFriend); mFriends = newFriends; } } loadList = true; } catch (JSONException e) { Log.e(TAG, e.toString()); } } break; case MYSPACE: break; case LINKEDIN: break; case FOURSQUARE: break; case IDENTICA: break; case GOOGLEPLUS: break; case CHATTER: break; } return loadList; } @Override protected void onPostExecute(Boolean loadList) { if (loadList) { // SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND}, new int[]{R.id.profile, R.id.name}); SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected }); sa.setViewBinder(mViewBinder); setListAdapter(sa); } if (loadingDialog.isShowing()) loadingDialog.dismiss(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); loadingDialog.show(); asyncTask.execute(mAccountId); }