List of usage examples for android.support.v4.widget SimpleCursorAdapter SimpleCursorAdapter
public SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags)
From source file:th.in.ffc.building.house.HouseListFragment.java
@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ContentResolver cr = getFFCActivity().getContentResolver(); if (mVillageSpinner != null) { Cursor villCursor = cr.query(Uri.withAppendedPath(Village.CONTENT_URI, "house"), VILL_PROJECTION, null, null, "village.villcode DESC"); SimpleCursorAdapter adapter = new SimpleCursorAdapter(getFFCActivity(), R.layout.village_list_item, villCursor, VILL_FROM, VILL_TO, SimpleAdapter.NO_SELECTION); mVillageSpinner.setAdapter(adapter); mVillageSpinner.setOnItemSelectedListener(this); if (villCursor.moveToFirst()) mVillId = villCursor.getLong(0); }/*from w w w . j a va2s . c om*/ if (mHouseTextView != null) { mHouseTextView.addTextChangedListener(this); } showProgess(true); mHouseAdapter = new HighLightCursorAdapter(getFFCActivity(), R.layout.house_list_item, null, HOUSE_FROM, HOUSE_TO); this.setListAdapter(mHouseAdapter); getLoaderManager().initLoader(0, null, this); }
From source file:fr.eoit.activity.ParameterActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.parameters); setProgressBarIndeterminate(true);/*from w w w . j av a2 s. c o m*/ setProgressBarIndeterminateVisibility(true); if (Parameters.keyId <= 0) { Toast.makeText(this, R.string.parameters_not_set, Toast.LENGTH_LONG).show(); } skillLoadingProgress = (ProgressBar) findViewById(R.id.SKILL_LIST_LOADING); receiver = new SkillUpdaterBroadcastReceiver(skillLoadingProgress); refreshCharacterSpinner(); // The names of the cursor columns to display in the view, initialized to the title column String[] dataColumns = { Item.COLUMN_NAME_NAME, Parameter.COLUMN_NAME_PARAM_VALUE }; // The view IDs that will display the cursor columns, initialized to the TextView in // noteslist_item.xml int[] viewIDs = { R.id.ITEM_NAME, R.id.SKILL_LEVEL_ICON }; // Creates the backing adapter for the ListView. adapter = new SimpleCursorAdapter(this, R.layout.skillrow, null, dataColumns, viewIDs, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); adapter.setViewBinder(new SkillListViewBinder()); skillListView = (ListView) findViewById(R.id.SKILLS_LIST); skillListView.setVisibility(View.GONE); // Sets the ListView's adapter to be the cursor adapter that was just created. skillListView.setAdapter(adapter); findViewById(R.id.location_management_layout).setOnClickListener(new GenericIntentLauncherOnClickListener( fr.eoit.db.bean.Station.CONTENT_URI, LocationManagementActivity.class, getApplicationContext())); findViewById(R.id.MINING_REGION_LAYOUT).setOnClickListener(new ParametersMiningSpaceOnClickListener(this)); findViewById(R.id.MINING_REGION_SEC_LAYOUT) .setOnClickListener(new ParametersMiningSecOnClickListener(this)); ((CheckBox) findViewById(R.id.MINING_SWITCH)).setChecked(Parameters.isMiningActive); ((CheckBox) findViewById(R.id.MINING_SWITCH)).setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Parameters.isMiningActive = isChecked; } }); initOrRestart(); }
From source file:alberthsu.sunshine.app.ForecastFragment.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // The SimpleCursorAdapter will take data from the database through the // Loader and use it to populate the ListView it's attached to. mForecastAdapter = new SimpleCursorAdapter(getActivity(), R.layout.list_item_forecast, null, // the column names to use to fill the textviews new String[] { WeatherEntry.COLUMN_DATETEXT, WeatherEntry.COLUMN_SHORT_DESC, WeatherEntry.COLUMN_MAX_TEMP, WeatherEntry.COLUMN_MIN_TEMP }, // the textviews to fill with the data pulled from the columns above new int[] { R.id.list_item_date_textview, R.id.list_item_forecast_textview, R.id.list_item_high_textview, R.id.list_item_low_textview }, 0);// ww w.j a va 2s . c o m mForecastAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { boolean isMetric = Utility.isMetric(getActivity()); switch (columnIndex) { case COL_WEATHER_MAX_TEMP: case COL_WEATHER_MIN_TEMP: { // we have to do some formatting and possibly a conversion ((TextView) view).setText(Utility.formatTemperature(cursor.getDouble(columnIndex), isMetric)); return true; } case COL_WEATHER_DATE: { String dateString = cursor.getString(columnIndex); TextView dateView = (TextView) view; dateView.setText(Utility.formatDate(dateString)); return true; } } return false; } }); View rootView = inflater.inflate(R.layout.fragment_main, container, false); // Get a reference to the ListView, and attach this adapter to it. ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast); listView.setAdapter(mForecastAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { Cursor cursor = mForecastAdapter.getCursor(); if (cursor != null && cursor.moveToPosition(position)) { Intent intent = new Intent(getActivity(), detailedActivity.class) .putExtra(detailedActivity.DATE_KEY, cursor.getString(COL_WEATHER_DATE)); startActivity(intent); } } }); return rootView; }
From source file:fr.eoit.activity.fragment.blueprint.RequiredBlueprintCopyInventionFragment.java
@Override protected void onLoadFinishedAdapteur(Cursor cursor, SimpleCursorAdapter adapter) { cursor.moveToFirst();/*w w w. jav a2 s. c om*/ long id = cursor.getLong(cursor.getColumnIndexOrThrow(Blueprint._ID)); int maxProductionLimit = (this.maxProdLimit / 10) > 1 ? cursor.getInt(cursor.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_MAX_PRODUCTION_LIMIT)) : 1; int baseCopyTime = cursor.getInt(cursor.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_RESEARCH_COPY_TIME)); double price = FormulaCalculator.calculateMaxRunsCopyCost(baseCopyTime, 1000, 4343, 1.5F, 0.5F); MatrixCursor blueprintCopyCursor = new MatrixCursor(new String[] { Blueprint._ID, Blueprint.COLUMN_NAME_NAME, ItemMaterials.COLUMN_NAME_QUANTITY, Prices.COLUMN_NAME_PRODUCE_PRICE }); String name = String.valueOf(maxProductionLimit) + " " + getResources().getText(R.string.blueprint_copy_str1) + " " + cursor.getString(cursor.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_NAME)); DbUtil.addRowToMatrixCursor(blueprintCopyCursor, id, name, numberOfChances, price); refreshAdapteur(new SimpleCursorAdapter(getActivity(), R.layout.item_row_small, blueprintCopyCursor, dataColumns, viewIDs, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER)); getAdapter().setViewBinder(new ItemListViewBinder(RedQuantityBehavior.PRICE)); if (fragmentReference.get() != null) { fragmentReference.get().setSingleBlueprintCopyPrice(price); } }
From source file:com.kncwallet.wallet.ui.SendingAddressesFragment.java
@Override public void onActivityCreated(final Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setEmptyText(getString(R.string.address_book_empty_text)); adapter = new SimpleCursorAdapter(activity, R.layout.address_book_row, null, new String[] { AddressBookProvider.KEY_RAW_TELEPHONE, AddressBookProvider.KEY_ADDRESS, AddressBookProvider.KEY_LABEL, AddressBookProvider.KEY_ADDRESS, AddressBookProvider.KEY_ADDRESS }, new int[] { R.id.address_book_row_number, R.id.address_book_contact_image, R.id.address_book_row_label, R.id.address_book_row_address, R.id.address_book_row_source_image }, 0);//from w w w . j av a 2 s.c o m adapter.setViewBinder(new ViewBinder() { @Override public boolean setViewValue(final View view, final Cursor cursor, final int columnIndex) { if (view.getId() == R.id.address_book_contact_image) { SmartImageView img = (SmartImageView) view; String address = cursor.getString(columnIndex); Bitmap contactImage = cachedBitmap(address); if (contactImage != null) { img.setImageBitmap(contactImage); } else { String imageUrl = cachedImageUrl(address); if (imageUrl != null) { img.setImageUrl(imageUrl, R.drawable.contact_placeholder); } else { img.setImageResource(R.drawable.contact_placeholder); } } return true; //true because the data was bound to the view } if (view.getId() == R.id.address_book_row_number) { ((TextView) view).setText(cursor.getString(columnIndex)); return true; } if (!AddressBookProvider.KEY_ADDRESS.equals(cursor.getColumnName(columnIndex))) return false; if (view.getId() == R.id.address_book_row_source_image) { ((ImageView) view).setImageResource(cachedSourceImageResource(cursor.getString(columnIndex))); view.setVisibility(View.VISIBLE); return true; } ((TextView) view).setText(WalletUtils.formatHash(cursor.getString(columnIndex), Constants.ADDRESS_FORMAT_GROUP_SIZE, 24)); return true; } }); setListAdapter(adapter); loaderManager.initLoader(0, null, this); getListView().setCacheColorHint(Color.TRANSPARENT); getListView().setBackgroundColor(getResources().getColor(R.color.knc_background_darker)); getView().setBackgroundColor(getResources().getColor(R.color.knc_background_darker)); }
From source file:com.meiste.tempalarm.ui.CurrentTemp.java
@Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.current_temp); ButterKnife.inject(this); mAdapter = new SimpleCursorAdapter(this, R.layout.record, null, FROM_COLUMNS, TO_FIELDS, 0); mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() { @Override/*from w w w .j av a 2 s.c o m*/ public boolean setViewValue(final View view, final Cursor cursor, final int columnIndex) { final TextView textView = (TextView) view; switch (columnIndex) { case COLUMN_TIMESTAMP: // Convert timestamp to human-readable date textView.setText(DateUtils.formatDateTime(getApplicationContext(), cursor.getLong(columnIndex), AppConstants.DATE_FORMAT_FLAGS)); return true; case COLUMN_DEGF: // Restrict to one decimal place textView.setText(String.format("%.1f", cursor.getFloat(columnIndex))); return true; case COLUMN_LIGHT: if (cursor.getInt(columnIndex) < mLightThreshold) { textView.setText(getText(R.string.lights_on)); } else { textView.setText(getText(R.string.lights_off)); } return true; } return false; } }); final View header = getLayoutInflater().inflate(R.layout.record_header, mListView, false); final FrameLayout frameLayout = ButterKnife.findById(header, R.id.graph_placeholder); mGraph = new LineGraphView(this, ""); mGraph.setDrawBackground(true); mGraph.setBackgroundColor(getResources().getColor(R.color.primary_graph)); mGraph.setCustomLabelFormatter(new CustomLabelFormatter() { @Override public String formatLabel(final double value, final boolean isValueX) { if (isValueX) { return DateUtils.formatDateTime(getApplicationContext(), (long) value, AppConstants.DATE_FORMAT_FLAGS_GRAPH); } return String.format(Locale.getDefault(), "%.1f", value); } }); mGraph.getGraphViewStyle().setNumHorizontalLabels(AppConstants.GRAPH_NUM_HORIZONTAL_LABELS); frameLayout.addView(mGraph); mListView.addHeaderView(header, null, false); mListView.setAdapter(mAdapter); getLoaderManager().initLoader(0, null, this); }
From source file:com.numenta.htmit.mobile.notification.NotificationListActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); gestureDetector = new GestureDetector(getApplicationContext(), this); setContentView(R.layout.activity_notification_list); setVisible(false);// w ww. jav a2s .c o m listView = (ListView) findViewById(R.id.notification_list_view); dismissButton = (Button) findViewById(R.id.action_dismiss_all_notifications); closeButton = (Button) findViewById(R.id.action_close_notifications); noNotificationsText = (TextView) findViewById(R.id.no_notifications_text); // For the cursor adapter, specify which columns go into which views String[] fromColumns = { "timestamp", "description", "metric_id", "read" }; int[] toViews = { R.id.notification_time, R.id.notification_description, R.id.notification_delete, R.id.notification_unread }; // The TextView in simple_list_item_1 _database = HTMITApplication.getDatabase(); adapter = new SimpleCursorAdapter(this, R.layout.fragment_notification_list_item, null, fromColumns, toViews, 0); new AsyncTask<Void, Void, Cursor>() { @Override protected Cursor doInBackground(Void... params) { unreadNotificationSize = _database.getUnreadNotificationCount(); return _database.getNotificationCursor(); } @Override protected void onPostExecute(Cursor cursor) { setVisible(true); adapter.changeCursor(cursor); notificationSize = cursor.getCount(); updateButtons(); } }.execute(); _notificationsReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (adapter != null) { new AsyncTask<Void, Void, Cursor>() { @Override protected Cursor doInBackground(Void... params) { if (isCancelled()) return null; return _database.getNotificationCursor(); } @Override protected void onPostExecute(Cursor cursor) { adapter.changeCursor(cursor); updateButtons(); } }.execute(); } } }; adapter.setViewBinder(new ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { final int viewId = view.getId(); switch (viewId) { case R.id.notification_time: // Converts the timestamp to a readable time. final int timeIndex = cursor.getColumnIndex("timestamp"); Date date = new Date(cursor.getLong(timeIndex)); ((TextView) view).setText(sdf.format(date)); break; case R.id.notification_unread: // Hides notification icon if already read. if (cursor.getInt(cursor.getColumnIndex("read")) < 1) { view.setVisibility(View.VISIBLE); } else { view.setVisibility(View.INVISIBLE); } break; case R.id.notification_delete: // Adds click handler for notification deletions view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "{TAG:ANDROID.ACTION.NOTIFICATION.DELETE} Delete notification clicked"); View layout = (View) v.getParent(); int position = listView.getPositionForView(layout); NotificationListActivity.this.removeNotificationAt(position); } }); break; default: return false; } return true; } }); listView.setAdapter(adapter); // Clicks on the notifications themselves navigates to the detail view. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { Log.i(TAG, "{TAG:ANDROID.ACTION.NOTIFICATION.SELECT} Notification navigation should occur here to notification " + position); Cursor cursor = (Cursor) adapter.getItem(position); int localIdx = cursor.getColumnIndex("_id"); final int localId = cursor.getInt(localIdx); new AsyncTask<Void, Void, Intent>() { @Override protected Intent doInBackground(Void... v) { // Get the metric necessary for the new intent to view // the metric detail // page. Notification notification = _database.getNotificationByLocalId(localId); if (notification == null) { // The notification or metric was deleted as the // user view the list return null; } Metric metric = _database.getMetric(notification.getMetricId()); if (metric == null) { // the metric was deleted, so nowhere to go _database.deleteNotification(localId); return null; } Intent metricDetail = NotificationUtils .createMetricDetailIntent(NotificationListActivity.this, notification); // Mark the notification as read if (!notification.isRead()) { _database.markNotificationRead(localId); } ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancelAll(); return metricDetail; } @Override protected void onPostExecute(Intent metricDetail) { if (metricDetail == null) { Toast.makeText(NotificationListActivity.this, R.string.notification_expired, Toast.LENGTH_LONG).show(); NotificationListActivity.this.finish(); return; } // Show detail page startActivity(metricDetail); // Hide the 'unread' indication. view.findViewById(R.id.notification_unread).setVisibility(View.INVISIBLE); } }.execute(); } }); // This catches "fling" events on items to delete notifications within // the list. // Defers touch events to a GestureDetector, which isolates fling events // from touch events. listView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } }); dismissButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.i(TAG, "{TAG:ANDROID.ACTION.NOTIFICATION.DELETE_ALL}"); deleteAllNotifications(); } }); closeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { cancelNotifications(); } }); }
From source file:nl.inversion.carexpense.ViewAllCars_Activity.java
private void displayListView() { // Load all cars in the cursor Cursor cursor = dbHelper.fetchAllCars(); /*//from w w w . jav a2 s. c om * Format data between SQLite and ListView: * SimpleCursorAdapter.ViewBinder * http://stackoverflow.com/questions/5851543/format-data-between-sqlite-and-listview * */ final ListView listView = (ListView) findViewById(R.id.viewAllCars); // The desired columns to be bound String[] columns = new String[] { DatabaseUtil.colCar_make, DatabaseUtil.colCar_model, DatabaseUtil.colCar_purDate, DatabaseUtil.colCar_licenseplate }; // the XML defined views which the data will be bound to int[] to = new int[] { R.id.make, R.id.model, R.id.pur_date, R.id.licenseplate }; // create the adapter using the cursor pointing to the desired data // as well as the layout information dataAdapter = new SimpleCursorAdapter(this, R.layout.car_listview, cursor, columns, to, 0); dataAdapter.setViewBinder(new CustomViewBinder()); // Assign adapter to ListView listView.setAdapter(dataAdapter); listView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) { // Get the cursor positioned to the corresponding item row of the item long-clicked Cursor cursor = (Cursor) listView.getItemAtPosition(position); // Get the ID from this row in the database. final int carIdSelected = cursor.getInt(cursor.getColumnIndexOrThrow("_id")); final String carMakeAndModelToRemove = cursor.getString(cursor.getColumnIndexOrThrow("make")) + " " + cursor.getString(cursor.getColumnIndexOrThrow("model")); AlertDialog.Builder adb = new AlertDialog.Builder(ViewAllCars_Activity.this); adb.setTitle(getString(R.string.Delete) + "?"); adb.setMessage(carMakeAndModelToRemove + "\n\n" + getString(R.string.DeleteText1)); adb.setNegativeButton(getString(R.string.Cancel), null); adb.setPositiveButton(getString(R.string.Delete), new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dbHelper.deleteCarID(carIdSelected); Toast.makeText(getApplicationContext(), carMakeAndModelToRemove + " " + getString(R.string.DeleteText2), Toast.LENGTH_LONG) .show(); // TODO proper update the list view instead of reloading entire intent finish(); startActivity(getIntent()); } }); adb.show(); return true; } }); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> listView, View view, int position, long id) { // Get the cursor positioned to the corresponding item row of the item long-clicked final Cursor cursor = (Cursor) listView.getItemAtPosition(position); // Get the ID from this row in the database. final int carIdSelected = cursor.getInt(cursor.getColumnIndexOrThrow("_id")); final String carMakeAndModel = cursor.getString(cursor.getColumnIndexOrThrow("make")) + " " + cursor.getString(cursor.getColumnIndexOrThrow("model")); AlertDialog.Builder adb = new AlertDialog.Builder(ViewAllCars_Activity.this); adb.setTitle(getString(R.string.EditOrShare) + "?"); adb.setMessage(carMakeAndModel + "\n\n" + getString(R.string.EditOrShareText)); adb.setPositiveButton(getString(R.string.Edit), new AlertDialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Start EditCar intent with extra data Intent EditCar = new Intent(getApplicationContext(), EditCar_Activity.class); EditCar.putExtra("CarID", cursor.getInt(cursor.getColumnIndexOrThrow("_id"))); dbHelper.close(); startActivityForResult(EditCar, 21); } }); adb.setNeutralButton(getString(R.string.Share), new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // TODO extend share method with proper data // Get data from DB back into List<String> List<String> carInfo = new ArrayList<String>(); carInfo = dbHelper.fetchAllCarDataFromID(carIdSelected); // Get all data from list into separate strings String carMake = carInfo.get(0); String carModel = carInfo.get(1); String carPurPrice = carInfo.get(2); String carPurDate = carInfo.get(3); String carMOT = carInfo.get(4); String carLicensePlate = carInfo.get(5); String carBuildDate = carInfo.get(6); // merge strings together String carInfoMerged = "See my car, a " + carMake + " " + carModel + " with license plate: " + carLicensePlate + ", build on " + carBuildDate + "/n I purchased it on " + carPurDate + " for " + carPurPrice; // Share string Intent shareCars = new Intent(android.content.Intent.ACTION_SEND); shareCars.setType("text/plain"); shareCars.putExtra(android.content.Intent.EXTRA_SUBJECT, getString(R.string.shareSubject) + " " + getString(R.string.app_name)); shareCars.putExtra(android.content.Intent.EXTRA_TEXT, carInfoMerged); startActivity(Intent.createChooser(shareCars, getString(R.string.shareVia))); } }); adb.show(); } }); }
From source file:com.groksolutions.grok.mobile.notification.NotificationListActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); gestureDetector = new GestureDetector(getApplicationContext(), this); setContentView(R.layout.activity_notification_list); setVisible(false);/*w w w . j a v a 2 s .c o m*/ listView = (ListView) findViewById(R.id.notification_list_view); dismissButton = (Button) findViewById(R.id.action_dismiss_all_notifications); closeButton = (Button) findViewById(R.id.action_close_notifications); noNotificationsText = (TextView) findViewById(R.id.no_notifications_text); // For the cursor adapter, specify which columns go into which views String[] fromColumns = { "timestamp", "description", "metric_id", "read" }; int[] toViews = { R.id.notification_time, R.id.notification_description, R.id.notification_delete, R.id.notification_unread }; // The TextView in simple_list_item_1 grokDb = HTMITApplication.getDatabase(); adapter = new SimpleCursorAdapter(this, R.layout.fragment_notification_list_item, null, fromColumns, toViews, 0); new AsyncTask<Void, Void, Cursor>() { @Override protected Cursor doInBackground(Void... params) { unreadNotificationSize = grokDb.getUnreadNotificationCount(); return grokDb.getNotificationCursor(); } @Override protected void onPostExecute(Cursor cursor) { setVisible(true); adapter.changeCursor(cursor); notificationSize = cursor.getCount(); updateButtons(); } }.execute(); _notificationsReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (adapter != null) { new AsyncTask<Void, Void, Cursor>() { @Override protected Cursor doInBackground(Void... params) { if (isCancelled()) return null; return grokDb.getNotificationCursor(); } @Override protected void onPostExecute(Cursor cursor) { adapter.changeCursor(cursor); updateButtons(); } }.execute(); } } }; adapter.setViewBinder(new ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { final int viewId = view.getId(); switch (viewId) { case R.id.notification_time: // Converts the timestamp to a readable time. final int timeIndex = cursor.getColumnIndex("timestamp"); Date date = new Date(cursor.getLong(timeIndex)); ((TextView) view).setText(sdf.format(date)); break; case R.id.notification_unread: // Hides notification icon if already read. if (cursor.getInt(cursor.getColumnIndex("read")) < 1) { view.setVisibility(View.VISIBLE); } else { view.setVisibility(View.INVISIBLE); } break; case R.id.notification_delete: // Adds click handler for notification deletions view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "{TAG:ANDROID.ACTION.NOTIFICATION.DELETE} Delete notification clicked"); View layout = (View) v.getParent(); int position = listView.getPositionForView(layout); NotificationListActivity.this.removeNotificationAt(position); } }); break; default: return false; } return true; } }); listView.setAdapter(adapter); // Clicks on the notifications themselves navigates to the detail view. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { Log.i(TAG, "{TAG:ANDROID.ACTION.NOTIFICATION.SELECT} Notification navigation should occur here to notification " + position); Cursor cursor = (Cursor) adapter.getItem(position); int localIdx = cursor.getColumnIndex("_id"); final int localId = cursor.getInt(localIdx); new AsyncTask<Void, Void, Intent>() { @Override protected Intent doInBackground(Void... v) { // Get the metric necessary for the new intent to view // the metric detail // page. Notification notification = grokDb.getNotificationByLocalId(localId); if (notification == null) { // The notification or metric was deleted as the // user view the list return null; } Metric metric = grokDb.getMetric(notification.getMetricId()); if (metric == null) { // the metric was deleted, so nowhere to go grokDb.deleteNotification(localId); return null; } Intent metricDetail = NotificationUtils .createMetricDetailIntent(NotificationListActivity.this, notification); // Mark the notification as read if (!notification.isRead()) { grokDb.markNotificationRead(localId); } ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancelAll(); return metricDetail; } @Override protected void onPostExecute(Intent metricDetail) { if (metricDetail == null) { Toast.makeText(NotificationListActivity.this, R.string.notification_expired, Toast.LENGTH_LONG).show(); NotificationListActivity.this.finish(); return; } // Show detail page startActivity(metricDetail); // Hide the 'unread' indication. view.findViewById(R.id.notification_unread).setVisibility(View.INVISIBLE); } }.execute(); } }); // This catches "fling" events on items to delete notifications within // the list. // Defers touch events to a GestureDetector, which isolates fling events // from touch events. listView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } }); dismissButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.i(TAG, "{TAG:ANDROID.ACTION.NOTIFICATION.DELETE_ALL}"); deleteAllNotifications(); } }); closeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { cancelNotifications(); } }); }
From source file:com.YOMPsolutions.YOMP.mobile.notification.NotificationListActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); gestureDetector = new GestureDetector(getApplicationContext(), this); setContentView(R.layout.activity_notification_list); setVisible(false);/*from w w w . j a va 2s .c o m*/ listView = (ListView) findViewById(R.id.notification_list_view); dismissButton = (Button) findViewById(R.id.action_dismiss_all_notifications); closeButton = (Button) findViewById(R.id.action_close_notifications); noNotificationsText = (TextView) findViewById(R.id.no_notifications_text); // For the cursor adapter, specify which columns go into which views String[] fromColumns = { "timestamp", "description", "metric_id", "read" }; int[] toViews = { R.id.notification_time, R.id.notification_description, R.id.notification_delete, R.id.notification_unread }; // The TextView in simple_list_item_1 YOMPDb = YOMPApplication.getDatabase(); adapter = new SimpleCursorAdapter(this, R.layout.fragment_notification_list_item, null, fromColumns, toViews, 0); new AsyncTask<Void, Void, Cursor>() { @Override protected Cursor doInBackground(Void... params) { unreadNotificationSize = YOMPDb.getUnreadNotificationCount(); return YOMPDb.getNotificationCursor(); } @Override protected void onPostExecute(Cursor cursor) { setVisible(true); adapter.changeCursor(cursor); notificationSize = cursor.getCount(); updateButtons(); } }.execute(); _notificationsReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (adapter != null) { new AsyncTask<Void, Void, Cursor>() { @Override protected Cursor doInBackground(Void... params) { if (isCancelled()) return null; return YOMPDb.getNotificationCursor(); } @Override protected void onPostExecute(Cursor cursor) { adapter.changeCursor(cursor); updateButtons(); } }.execute(); } } }; adapter.setViewBinder(new ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { final int viewId = view.getId(); switch (viewId) { case R.id.notification_time: // Converts the timestamp to a readable time. final int timeIndex = cursor.getColumnIndex("timestamp"); Date date = new Date(cursor.getLong(timeIndex)); ((TextView) view).setText(sdf.format(date)); break; case R.id.notification_unread: // Hides notification icon if already read. if (cursor.getInt(cursor.getColumnIndex("read")) < 1) { view.setVisibility(View.VISIBLE); } else { view.setVisibility(View.INVISIBLE); } break; case R.id.notification_delete: // Adds click handler for notification deletions view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i(TAG, "{TAG:ANDROID.ACTION.NOTIFICATION.DELETE} Delete notification clicked"); View layout = (View) v.getParent(); int position = listView.getPositionForView(layout); NotificationListActivity.this.removeNotificationAt(position); } }); break; default: return false; } return true; } }); listView.setAdapter(adapter); // Clicks on the notifications themselves navigates to the detail view. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { Log.i(TAG, "{TAG:ANDROID.ACTION.NOTIFICATION.SELECT} Notification navigation should occur here to notification " + position); Cursor cursor = (Cursor) adapter.getItem(position); int localIdx = cursor.getColumnIndex("_id"); final int localId = cursor.getInt(localIdx); new AsyncTask<Void, Void, Intent>() { @Override protected Intent doInBackground(Void... v) { // Get the metric necessary for the new intent to view // the metric detail // page. Notification notification = YOMPDb.getNotificationByLocalId(localId); if (notification == null) { // The notification or metric was deleted as the // user view the list return null; } Metric metric = YOMPDb.getMetric(notification.getMetricId()); if (metric == null) { // the metric was deleted, so nowhere to go YOMPDb.deleteNotification(localId); return null; } Intent metricDetail = NotificationUtils .createMetricDetailIntent(NotificationListActivity.this, notification); // Mark the notification as read if (!notification.isRead()) { YOMPDb.markNotificationRead(localId); } ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancelAll(); return metricDetail; } @Override protected void onPostExecute(Intent metricDetail) { if (metricDetail == null) { Toast.makeText(NotificationListActivity.this, R.string.notification_expired, Toast.LENGTH_LONG).show(); NotificationListActivity.this.finish(); return; } // Show detail page startActivity(metricDetail); // Hide the 'unread' indication. view.findViewById(R.id.notification_unread).setVisibility(View.INVISIBLE); } }.execute(); } }); // This catches "fling" events on items to delete notifications within // the list. // Defers touch events to a GestureDetector, which isolates fling events // from touch events. listView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return gestureDetector.onTouchEvent(event); } }); dismissButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.i(TAG, "{TAG:ANDROID.ACTION.NOTIFICATION.DELETE_ALL}"); deleteAllNotifications(); } }); closeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { cancelNotifications(); } }); }