w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
CursorLoader does not refresh if notifyChange() is called before CursorLoader registers ContentObserver
My approach is to register the observer before starting with the loading of the cursor. You need to register for the Uri instead of for the cursor. getActivity().getContentResolver().registerContentObserver( your_Uri, true, new YourObserver(mHandler)); getLoaderManager().initLoader(0, null, this);

Categories : Android

AutoCompletetextView with CursorLoader
This is a fine approach, according to the android developer website : Restarting a Loader : To discard your old data, you use restartLoader(). For example, this implementation of SearchView.OnQueryTextListener restarts the loader when the user's query changes. The loader needs to be restarted so that it can use the revised search filter to do a new query:

Categories : Android

How do I go about implementing CursorLoader without using a Listview?
Is it possible to extract the information from the returned adapter There is no "returned adapter". CursorLoader is a Loader that returns a Cursor. None of those things are "adapters" as the term is used in Android. and update the TextViews inside the ViewGroups? Yes. The Cursor API allows you to set which row you want to work with (moveToPosition(), etc.), from which you can retrieve columns (getString(), etc.). Do I need to re-write it to use a Loader? CursorLoader works only with a ContentProvider. If your DatabaseHelper (presumably a subclass of SQLiteOpenHelper) is used by a ContentProvider, then your CursorLoader can work with that ContentProvider. Other alternatives include: not bothering with the Loader framework, and just using AsyncTask and kin for doing your

Categories : Android

LoaderManager/CursorLoader for several cursors?
it shouldn't be necessary to bind to two different cursors in your case (and i wouldn't recommend it, since you would have to write your own adapter in that case). Try to query across your tables instead, check this for a starting point: SQLite query from multiple tables using SQLiteDatabase how to use join query in CursorLoader when its constructor does not support it For your second question, if you don't want to expose your ContentProvider to other applications set: <provider .... android:exported="false"> </provider> in your manifest

Categories : Android

AutoCompleteTextView with CursorLoader and SimpleCursorAdapter
After some investigation, it seems that SimpleCursorAdapter inherits from ResourceCursorAdapter, which inherits from CursorAdapter. CursorAdapter uses CursorFilter for filtering, and this class calls changeCursor() in its publishResults(). changeCursor closes the old cursor... So that's why my cursors were closed automatically. I dropped the loaders, and changed the implementation to the code below, and it works greatly: mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, mTagDbLoader.fetchAll(), new String[] { DbConstants.Tags.KEY_TAG }, new int[] { android.R.id.text1 }, 0); mAdapter.setFilterQueryProvider(new FilterQueryProvider() { @Override public Cursor runQuery(CharSequence constraint) { if (constraint ==

Categories : Android

How to read an SQLite DB in android with a cursorloader?
These are the steps to create a cursorloader in a list fragment 1) Create a class extending SQLiteOpenHelper and override onCreate and onUpgrade to create your tables. 2) Create a class extending ContentProvider and create the URIs to access your database. Refer http://developer.android.com/guide/topics/providers/content-providers.html. Add your URIs to the URIMatcher which you use in onCreate, onUpdate, query, etc (overridden methods) to match the URI. Refer http://developer.android.com/reference/android/content/UriMatcher.html 3) In the insert method call getContext().getContentResolver().notifyChange(uri, null). In the query method call setNotificationUri(ContentResolver cr, Uri uri) before returning the content provider for the insertion change to reflect automatically to your load

Categories : Android

Cursorloader not refreshing when underlying data changes
I see that you aren't calling swapCursor or changeCursor in your onLoadFinished and onLoaderReset. You need to do that for your adapter to access the data loaded into the new cursor. in onLoadFinished, call something like: mAdapter.swapCursor(cursor) In onLoaderReset, call this to remove references to the old cursor: mAdapter.swapCursor(null) Where mAdapter is your listView's adapter. More info: http://developer.android.com/guide/components/loaders.html#onLoadFinished

Categories : Android

AutoCompleteTextView populated by contacts using CursorLoader
Since no one else has offered an answer, let me suggest populating your array in onLoaderFinish after the cursor has been created. The Cursor Loader is essentially a query statement and not the results, which is why you can't cast from a CursorLoader to a Cursor.

Categories : Android

FragmentActivity, CursorLoader and getActivity undefined
FragmentActivity does not have any getActivity() method like Fragment have. If you want to get the activity you should use this keyword inside FragmentActivity.

Categories : Android

Testing a CursorLoader with Robolectric & Mockito
I've just gotten Loader tests working in my code. In my case I found it more direct to test the loader itself rather than try to route it through the Fragment code. I wound up using a slightly modified version of the code from this post: https://groups.google.com/forum/#!msg/robolectric/xY5MF399jA8/V5PnUfh1D-wJ First, I had to implement some shadow classes because Robolectric2 doesn't include shadow code for the AsyncTaskLoader or Loader classes. If you've never added a shadow class know that it's important you put these in the correct package. Both of these shadows should live in android.support.v4.content. ShadowLoader @Implements(Loader.class) public class ShadowLoader<D> { // ////////////////////// // Constants // ////////////////////// // Fields protected boolean res

Categories : Android

ListView: filtering via Filterable vs. restarting CursorLoader with new URI
Was the filtering mechanism for ListView designed also for the cursor based data? The filtering mechanism through the Filter class was implemented for the adapter(a logical action to do with an adapter), the ListView is just a simple user of that adapter. When the Filterable should be used and when filter should be passed to the SQL query without using ListView filters? Are there any recommendations when this or that approach should be used? I don't think there are any recommendation on which one to use(or I didn't see them myself). The Filter class however is specially designed to optimize the filtering process(for example if the initial filtering operation takes some time and the user makes other requests in this time, then the Filter class will only perform the last fil

Categories : Android

Android CursorLoader > ContentProvider > SqliteDatabase not working
I dont see you calling setNotificatioUri on the cursor before you return it have a look at one of my query methods that I know works @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder(); sqlBuilder.setTables(CAL_EVENTS_TABLE); if (uriMatcher.match(uri) == 1) { sqlBuilder.setProjectionMap(mMap); } else if (uriMatcher.match(uri) == 2) { sqlBuilder.setProjectionMap(mMap); sqlBuilder.appendWhere(ID + "=?"); selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs, new String[] { uri.getLastPathSegment() }); } if (sortOrder == null || sortOrder == "") sortOrder = START_DATE

Categories : Android

Android: How can I get DISPLAY_NAME & COMPANY name of all contact the same time by using cursorloader?
I think you need to look at querying against the ContactsContract.Data There is an example of joining and pulling in additional data from the contact in the docs along with this special constant ContactsContract.CommonDataKinds.Organization.COMPANY

Categories : Android

Android: Can't access cursor data inside ContentProvider using CursorLoader
Because the cursor row values are null, The Cursor values aren't null(or at least this isn't the reason for the error) it's the cur reference that is null. When you first initialize the adapter you do it with a null Cursor(at this point cur is null). When your loader does its job and loads the data you call swapCursor() and the adapter will start building rows, unfortunately your cur reference will continue to be null as it doesn't get magically updated with the new Cursor reference. By the way, i forgot to say, if in the Activity instead using MarcaCursorAdapter i just use SimpleCursorAdapter (losing the customization of my method getView) the list loads without problems and showing the data, This is happening because of your implementation of the getView() method. First

Categories : Android

Android CursorLoader adding views dynamically in specific/certain order
How can I get the views in the correct order I want them in without having a bunch of boolean variables? You do need some sort of status control in order to make the views appear in order. I would delegate the view construction/addition to a control class that will have all the information required to make the correct view and in the right order no matter how the loaders finished their jobs. public class ViewDispatcher { public SparseArray<Status> mLoadStatuses = new SparseArray<Status>(); public SparseArray<Cursor> mDataCursors = new SparseArray<Cursor>(); // you'll call this method for each of the loaders, in the order they should be. The ids should be incremental public void registerLoader(int loaderId) { mLoadStatuses.put(loaderI

Categories : Android

Check SQLite database for duplicate entries, CursorLoader/Loader/AsyncTaskLoader? Confusion
An AsyncTask runs code on a non-UI (usually called a "background") thread. An AsyncTask can do anything, but it's a bit fragile because it disappears if the system restarts the Activity that started the AsyncTask. This can happen quite easily, because the system restarts the current Activity if the user rotates the device (unless you trap onSystemConfigurationChanged). Formally, an AsyncTaskLoader is a Loader that uses AsyncTask to run its code. This means in real terms that an AsyncTaskLoader gets data from somewhere by using a non-UI thread (the AsyncTask part). The loader part just gives you convenience methods for dealing with the process of getting data, which may take a long time. The loader part also lets you track the data and restart the load if the data changes. Based on what y

Categories : Android

DRY cache miss handling in java
In java, you can do (a transliteration of your code): public String getUsingWayOne(){ String retval = WayOneCacheClass.execute(); if (retval != null && !retval.isEmpty()) { return retval; return WayOneDiskClass.execute(); } Note that I've made the execute() method static, because it's obviously stateless. Or set up the two ways in an instance (without knowing more, this is what I'd do): public interface Cacher { execute(); } public class TwoWayCacher { private final Cacher one; private final Cacher two; pubic TwoWayCacher (Cacher one, Cacher two) { this.one = one; this.two = two; } public String get() { String retval = one.execute(); if (retval != null && !retval.isEmpty()) { return r

Categories : Java

Cache miss in an Out of order processor
As is the case with most micro-architectural features, the safe answer would be - "it might, and it might not - depends on the exact characteristics of your application". Take for e.g. a workload that runs through a large graph that resides in the memory - each new node needs to be fetched and processed before the new node can be chosen. If you reduce the frequency you would harm the execution phase which is latency critical since the next set of memory accesses depends on it. On the other hand, a workload that is bandwidth-bounded (i.e.- performs as fast as the system memory BW limits), is probably not fully utilizing the CPU and would therefore not be harmed as much. Basically the question boils down to how well your application utilizes the CPU, or rather - where between the CPU and th

Categories : Caching

java + can we miss signals using wait and notify?
With wait and notify you should always wait based on a condition notify which changes the state checked by the wait. Note: it is possible for wait() to wake spuriously so you cannot assume a notify() was called. Can't we avoid the missed signals using wait and notify alone ? No, you never could which is why it was always assumed it would be associated with a state change. e.g. A common interview question is to write a simple blocking Queue. // a simple blocking queue using an AtomicReference final Object lock = new Object(); final E eRef = null; public void push(E e) { synchronized(lock) { while(eRef != null) lock.wait(); eRef = e; lock.notifyAll(); } } public E take() { synchronized(lock) { while(eRef == null)

Categories : Java

I should avoid static compilation because of cache miss?
The overall memory footprint of the static version is the same as that of the dynamic version; remember that the dynamically-linked objects still need to be loaded into memory! Of course, one could also argue that if there are multiple processes running, and they all dynamically link against the same object, then only one copy is required in memory, and so the aggregate footprint is lower than if they had all statically linked. [Disclaimer: all of the above is educated guesswork; I've never measured the effect of linking on cache behaviour.]

Categories : C++

Is it possible to see the queries that caused an index miss in Mongodb
You should be aware that indexCounters.btree.misses does not indicate that a value was not found in an index; it means that an index page was not in memory when the server tried to access it, and so it had to be paged in. A query that does not find a particular value in an index would simply be a query that does not find a result to satisfy the query. One way to log "problematic" queries is with the slowms option. Any query that takes longer than a given number of milliseconds is then written to the log file. You specify slowms as an optional second argument to db.setProfilingLevel(), see here for details.

Categories : Mongodb

DTLB miss number counting discrepency
That is expected since the first event counts the number of misses to all TLB levels caused by all possible reasons (load, store, pre-fetch), including memory accesses performed speculatively, while the other two events count only retired (that is, non-speculative) load and store operations, and only those among them that didn’t cause any fault. Please refer to Chapter 19.6 of Volume 3 of Intel® 64 and IA-32 Architectures Software Developer’s Manual. Thanks, Stas

Categories : Misc

why does my for loop miss the first element in the NSMutableArray on which it operates?
The only thing which is wrong in the code is below statement: [pID release]; You have not allocated it so you do not need to destroy it. Rest everything looks fine. One more change is also required. In below line, you are passing pId as string. You should pass it as number. NSNumber *pID = [NSNumber numberWithLongLong:[[self.songArray objectAtIndex:i] longLongValue]]; [cellQuery addFilterPredicate:[MPMediaPropertyPredicate predicateWithValue:pID forProperty:MPMediaItemPropertyPersistentID]];

Categories : IOS

Query an object but miss out field/Property (Soda)
Well, the easiest solution (IMHO) is to wrap the BitMap class in another class and use db4o's transparent activation feature: using System; using System.IO; using System.Linq; using Db4objects.Db4o; using Db4objects.Db4o.Activation; using Db4objects.Db4o.TA; namespace ActivationDepth { class Program { static void Main(string[] args) { var dbFilePath = Path.GetTempFileName(); using (var db = Db4oEmbedded.OpenFile(dbFilePath)) { db.Store(new C1 { Name = "c1", Huge = new MyHugeClass("I am really huge....")}); } var config = Db4oEmbedded.NewConfiguration(); config.Common.Add(new TransparentActivationSupport()); config.Common.ActivationDepth = 0; using (var

Categories : C#

Different cache miss count for a same program between multiple runs
Linux implements the "Address space layout randomization" technique (http://en.wikipedia.org/wiki/Address_space_layout_randomization) for security matters. And you can deactivate this behavior like this: echo -n "0" > /proc/sys/kernel/randomize_va_space You can test that through this example: #include <stdio.h> int main() { char a; printf("%u ", &a); return 0; } You should always have the same value printed. Before: % ./a.out 4006500239 % ./a.out 819175583 % ./a.out 2443759599 % ./a.out 2432498159 After: % ./a.out 4294960207 % ./a.out 4294960207 % ./a.out 4294960207 % ./a.out 4294960207 That also explain the different amount of cache misses since two variables that were in the same line can now be in two different lines. Edit: This does not solv

Categories : C

Will I miss any changes if I replace an oracle trigger while my application is running?
I think you might be going about testing this in the wrong way. Your insert statements won't take any time at all and so the replacement of the trigger can fit in through the gaps between inserts. As least this is what I infer due to the below. If you change your test to ensure you have a long running SQL statement, e.g. create table test_trigger (id number); create table test_trigger_h (id number); create sequence test_trigger_seq; create or replace trigger test_trigger_t after insert on test_trigger for each row begin insert into test_trigger_h (id) values (:new.id); end; / insert into test_trigger select level from dual connect by level <= 1000000; If you then try to replace the trigger in a separate session it will not occur until after the insert has completed. U

Categories : Oracle

Rectify miss formating of text in mysql column
Assuming that "Numbers" only appears once in VolumeNumber, something like this should do it: UPDATE SomeTable SET VolumeNumber = REPLACE(VolumeNumber, 'Numbers ', ' Numbers ') WHERE VolumeNumber NOT LIKE '% Numbers%' ;

Categories : Mysql

Safe Bool Idiom - did I find a simpler way, or did I miss something?
Your technique works, and is discussed as one of the http://www.artima.com/cppsource/safebool.html . It discusses it as an option that works. It is called "poisoning operators" and Douglas Gregor is credited with inventing it. I think the real safe_bool idiom got more headway by being even more safe. In particular, if your safe_bool is of type int T::*, and the only pointer to an integer member of T is private, then only that class can generate that particular variant of safe_bool, so its even easier to prove that no one can generate unsafe patterns. Since anyone can take the address of &SafeBool::Value, it is "less safe." Pathological? Perhaps.

Categories : C++

Java JsonObject miss the fields when convert object to Json
Your object facebook needs a getter for every field. Take a look to the documentation: public JSONObject(java.lang.Object bean) Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each of the methods with no parameters and a name starting with "get" or "is" followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. The key is formed by removing the "get" or "is" prefix. If the second remaining character is not upper case, then the first character is converted to lower case. For example, if an object has a method named "getName", and if the result of calling object.getName() is "Larry Fine", then the JSONObject wil

Categories : Java

C# AES RijndaelManaged() CBC and PaddingMode.Zeros seems to miss 16 chars after post to PHP JSON
CryptoStream doesn't automatically prepend the IV to the ciphertext. The PHP side is chopping off the first block of the message and using that as the IV. Here's some sample PHP that reproduces the problem: $ivSize = 32; $key = hash('SHA256', 'hello world', true); $iv = mcrypt_create_iv($ivSize); $cipher = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, "This is some sample text where the first block will be cut off.", MCRYPT_MODE_CBC, $iv); $firstBlock = substr($cipher, 0, $ivSize); $remainingCipher = substr($cipher, $ivSize); $plain = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $remainingCipher, MCRYPT_MODE_CBC, $firstBlock); echo $plain; Outputs: he first block will be cut off.

Categories : C#

number of cache hits/miss vs page faults - C++ code - UBUNTU
The most comprehensive profiling tool for linux is oprofile, which can profile single applications or your entire system, and can give you detailed information about cache misses (and where they are occurring) on processors that support performance counters for events like cache misses (pretty much all x86 processors made for the past 20 years support such counters) Page faults have nothing to do with cache misses, though they are also a potential source of performance problems.

Categories : C++

rdtsc code that shows performance impacts from memory characterstics such as TLB miss
This code is simply looping through a 2MB buffer, writing 0 to each byte of it, and computing the time it takes to perform each write, updating a low- and high-water mark (min and max) that show the shortest & longest times required for making each write. Assuming this program is the ONLY program running on the CPU, and assuming no asynchronous events occur while it's running (hardware interrupts or timer interrupts), this program would show you both the nominal time for making a byte-wide write to memory, and the maximum amount of time required for handling a TLB miss exception and/or page fault exception. A TLB miss exception is an exception that the core takes when a program tries to access memory for which there is not a TLB entry in the MMU. The MMU is the police officer at the

Categories : C

PhoneGap/Cordova Error: Miss a drag as we are waiting for WebCore's response for touch down
I fixed this issue by listening to 'touchstart' event, and preventingDefault. $('.element').on('touchmove', function(ev) { ev.preventDefault(); }); The problem, though, it also cancel all the scroll events if there is any in the '.element' element.

Categories : Cordova

How to avoid TLB miss (and high Global Memory Replay Overhead) in CUDA GPUs?
You can only avoid TLB misses by changing your memory access pattern. A different layout of your data in memory can help with this. A 3D texture will not improve your situation, as it trades improved spatial locality in two additional dimensions against reduced spatial locality in the third dimension. Thus you would unnecessarily read data of neighbors along the Y axis. What you can do however is mitigate the impact of the resulting latency on throughput. In order to hide t = 700 cycles of latency at a global memory bandwidth of b = 250GB/s, you need to have memory transactions for b / t = 175 KB of data in flight at any time (or 12.5 KB for each of the 14 SMX). With a fully loaded memory interface and a high ratio of TLB misses, you will however find that latency gets closer to 2000 cy

Categories : Caching

previous correct radio buttons disappearing when i miss a radio button in the middle
You could simply change: onclick="validate()" to: onclick="return validate()" and it will have the desired behavior. I think this is what you were trying to do, but the onclick() call never returned the value from validate().

Categories : Javascript

Default instance for a named instance miss
Use var x = ObjectFactory.TryGetInstance<IX>("delta") ?? ObjectFactory.GetInstance<IX>(); provided that you have registered the Default class as a default instance. The Use method registers default instances and the Add method adds additional instances. i.For<IX>().Use<Default>(); i.For<IX>().Add<Alpha>().Named("alpha"); i.For<IX>().Add<Bravo>().Named("bravo"); i.For<IX>().Add<Charlie>().Named("charlie");

Categories : C#

MS SQL Index value updates
You need to lock the table for the duration of the transaction. Other threads will wait until the transaction finishes (commit or rollback). SET TRANSACTION ISOLATION LEVEL REPEATABLE READ BEGIN TRANSACTION --do stuff COMMIT TRANSACTION http://msdn.microsoft.com/en-us/library/ms173763.aspx

Categories : Sql Server

Delta Updates Api
You do not need to do anything to utilize this feature. It is the default behavior for all apps on the Google Play Store as of Jelly Bean (4.2, API 17).

Categories : Android

Some FTP updates don't take effect, some do
It has happened to me a couple of times. In my case, the source files have path from "cdn", so we usually purge cdn cache for changes to be reflected on the server. Is your case similar?

Categories : PHP

location updates through 3g
To retrieve the location from a NETWORK_PROVIDER you can use the following: LocationListener locationListenerNetwork = new LocationListener() { public void onLocationChanged(Location location) { timer1.cancel(); locationResult.gotLocation(location); lm.removeUpdates(this); lm.removeUpdates(locationListenerGps); } public void onProviderDisabled(String provider) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} }; LocationManager lm; if(lm==null) lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); This is however a basic example, so to distinguish between the wi-fi and the 3g network first take a look here and before the code above do:

Categories : Android



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.