Search Results

Search found 312 results on 13 pages for 'invalidate'.

Page 10/13 | < Previous Page | 6 7 8 9 10 11 12 13  | Next Page >

  • iPhone slide view passing variables

    - by sebastyuiop
    Right, I'm trying to make an app that has a calculation that involves a stopwatch. When a button on the calculation view is clicked a stopwatch slides in from the bottom. This all works fine, the problem I can't get my head around is how to send the recorded time back to the previous controller to update a textfield. I've simplified the code and stripped out most irrelevant stuff. Many thanks. CalculationViewController.h #import <UIKit/UIKit.h> @interface CalculationViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { IBOutlet UITextField *inputTxt; } @property (nonatomic, retain) UITextField *inputTxt; - (IBAction)showTimer:(id)sender; @end CalculationViewController.m #import "CalculationViewController.h" #import "TimerViewController.h" @implementation CalculationViewController - (IBAction)showTimer:(id)sender { TimerViewController *timerView = [[TimerViewController alloc] init]; [self.navigationController presentModalViewController:timerView animated:YES]; } TimerViewController.h #import <UIKit/UIKit.h> @interface TimerViewController : UIViewController { IBOutlet UILabel *time; NSTimer *myTicker; } - (IBAction)start; - (IBAction)stop; - (IBAction)reset; - (void)showActivity; @end TimerViewController.m #import "TimerViewController.h" #import "CalculationViewController.h" @implementation TimerViewController - (IBAction)start { myTicker = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil repeats:YES]; } - (IBAction)stop { [myTicker invalidate]; #Update inputTxt on calculation view here [self dismissModalViewControllerAnimated:YES]; } - (IBAction)reset { time.text = @"0"; } - (void)showActivity { int currentTime = [time.text intValue]; int newTime = currentTime + 1; time.text = [NSString stringWithFormat:@"%d", newTime]; } @end

    Read the article

  • xml vs java LinearLayout fills

    - by user293443
    the xml version below properly handles height and width and the java doesn't what is the java missing? xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="horizontal"> <include android:id="@+id/cell1" layout="@layout/grid_text_view" /> <include android:id="@+id/cell2" layout="@layout/grid_text_view" /> </LinearLayout> java LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.HORIZONTAL); ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); ll.addView((TextView)this.getLayoutInflater().inflate(R.layout.grid_text_view, null)); ll.addView((TextView)this.getLayoutInflater().inflate(R.layout.grid_text_view, null)); setContentView(ll); grid_text_view <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="0dip" android:text="1" android:textSize="20sp" android:gravity="center" android:layout_weight="1" /> I've tried a ll.invalidate() and it didn't work either? :( screenshots at http://www.flickr.com/photos/48409507@N06/sets/72157623618407586/

    Read the article

  • NSOperation for animation loop causes strange scrolling behaviour

    - by Tricky
    Hi, I've created an animation loop which I run as an operation in order to keep the rest of my interface responsive. Whilst almost there, there is still one remaining issue. My UIScrollViews don't seem to be reliably picking up when a user touch ends. What this means is, for example, if a user drags down on a scroll view, when they lift their fingers the scrollview doesn't bounce back into place and the scrollbar remains visible. As if the finger hasn't left the screen. It takes another tap on the scrollview for it to snap to its correct position and the scrollbar to fade away... Here's the loop I created in a subclassed NSOperation: (void)main { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; _displayLink = [[CADisplayLink displayLinkWithTarget: self selector: @selector(animationLoop:)] retain]; [_displayLink setFrameInterval: 1.0f]; [_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode: NSRunLoopCommonModes]; while (![self isCancelled]) { NSAutoreleasePool *loopPool = [[NSAutoreleasePool alloc] init]; [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; [loopPool drain]; } [_displayLink invalidate]; [pool release]; } DOes anyone have any idea what might be going on here, and even better how to fix it... Thanks!

    Read the article

  • Caching Authentication Data

    - by PartlyCloudy
    Hi, I'm currently implementing a REST web service using CouchDB and RESTlet. The RESTlet layer is mainly for authentication and some minor filtering of the JSON data served by CouchDB: Clients <= HTTP = [ RESTlet <= HTTP = CouchDB ] I'm using CouchDB also to store user login data, because I don't want to add an additional database server for that purpose. Thus, each request to my service causes two CouchDB requests conducted by RESTlet (auth data + "real" request). In order to keep the service as efficent as possible, I want to reduce the number of requests, in this case redundant requests for login data. My idea now is to provide a cache (i.e.LRU-Cache via LinkedHashMap) within my RESTlet application that caches login data, because HTTP caching will probabily not be enough. But how do I invalidate the cache data, once a user changes the password, for instance. Thanks to REST, the application might run on several servers in parallel, and I don't want to create a central instance just to cache login data. Currently, I save requested auth data in the cache and try to auth new requests by using them. If a authentication fails or there is now entry available, I'll dispatch a GET request to my CouchDB storage in order to obtain the actual auth data. So in a worst case, users that have changed their data will perhaps still be able to login with their old credentials. How can I deal with that? Or what is a good strategy to keep the cache(s) up-to-date in general? Thanks in advance.

    Read the article

  • C# reference collection for storing reference types

    - by ivo s
    I like to implement a collection (something like List<T>) which would hold all my objects that I have created in the entire life span of my application as if its an array of pointers in C++. The idea is that when my process starts I can use a central factory to create all objects and then periodically validate/invalidate their state. Basically I want to make sure that my process only deals with valid instances and I don't re-fetch information I already fetched from the database. So all my objects will basically be in one place - my collection. A cool thing I can do with this is avoid database calls to get data from the database if I already got it (even if I updated it after retrieval its still up-to-date if of course some other process didn't update it but that a different concern). I don't want to be calling new Customer("James Thomas"); again if I initted James Thomas already sometime in the past. Currently I will end up with multiple copies of the same object across the appdomain - some out of sync other in sync and even though I deal with this using timestamp field on the MSSQL server I'd like to keep only one copy per customer in my appdomain (if possible process would be better). I can't use regular collections like List or ArrayList for example because I cannot pass parameters by their real local reference to the their existing Add() methods where I'm creating them using ref so that's not to good I think. So how can this be implemented/can it be implemented at all ? A 'linked list' type of class with all methods working with ref & out params is what I'm thinking now but it may get ugly pretty quickly. Is there another way to implement such collection like RefList<T>.Add(ref T obj)? So bottom line is: I don't want re-create an object if I've already created it before during the entire application life unless I decide to re-create it explicitly (maybe its out-of-date or something so I have to fetch it again from the db). Is there alternatives maybe ?

    Read the article

  • How to determine Scale of Line Graph based on Pixels/Height?

    - by Dexter
    I have a problem due to my terrible math abilities, that I cannot figure out how to scale a graph based on the maximum and minimum values so that the whole graph will fit onto the graph-area (400x420) without parts of it being off the screen (based on a given equation by user). Let's say I have this code, and it automatically draws squares and then the line graph based on these values. What is the formula (what do I multiply) to scale it so that it fits into the small graphing area? vector<int> m_x; vector<int> m_y; // gets automatically filled by user equation or values int HeightInPixels = 420;// Graphing area size!! int WidthInPixels = 400; int best_max_y = GetMaxOfVector(m_y); int best_min_y = GetMinOfVector(m_y); m_row = 0; m_col = 0; y_magnitude = (HeightInPixels/(best_max_y+best_min_y)); // probably won't work magnitude = (WidthInPixels/(int)m_x.size()); m_col = m_row = best_max_y; // number of vertical/horizontal lines to draw ////x_magnitude = (WidthInPixels/(int)m_x.size())/2; Doesn't work well ////y_magnitude = (HeightInPixels/(int)m_y.size())/2; Doesn't work well ready = true; // we have values, graph it Invalidate(); // uses WM_PAINT

    Read the article

  • C#- move a shape to a point which is half way from the top of the form

    - by hello-all
    Hello all, Here I have to create a diamond using drawlines method and make it move horizontally along a path that is half way from the top of the form. I created a diamond and it is moving horizontally, but i want it to start moving from a position which is half way from the top of the form. This is the code to create a diamond, private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; Point p1 = new Point(5+x, 0); Point p2 = new Point(10+x, 5); Point p3 = new Point(5+x, 10); Point p4 = new Point(0+x, 5); Point[] ps = { p1, p2, p3, p4, p1 }; Pen p_yellow = new Pen(Color.Yellow, 5); g.DrawLines(p_yellow, ps); this.BackColor = System.Drawing.Color.DarkBlue; } I can make it move using the timer and following is the code, private void timer1_Tick(object sender, EventArgs e) { if (x < 500) x += 2; else timer1.Enabled = false; this.Invalidate(); } please tell me how to bring the diamond to a point which is half way from the top of the form?

    Read the article

  • WriteableBitmap failing badly, pixel array very inaccurate

    - by dawmail333
    I have tried, literally for hours, and I have not been able to budge this problem. I have a UserControl, that is 800x369, and it contains, simply, a path that forms a worldmap. I put this on a landscape page, then I render it into a WriteableBitmap. I then run a conversion to turn the 1d Pixels array into a 2d array of integers. Then, to check the conversion, I wire up the custom control's click command to use the Point.X and Point.Y relative to the custom control in the newly created array. My logic is thus: wb = new WriteableBitmap(worldMap, new TranslateTransform()); wb.Invalidate(); intTest = wb.Pixels.To2DArray(wb.PixelWidth); My conversion logic is as such: public static int[,] To2DArray(this int[] arr,int rowLength) { int[,] output = new int[rowLength, arr.Length / rowLength]; if (arr.Length % rowLength != 0) throw new IndexOutOfRangeException(); for (int i = 0; i < arr.Length; i++) { output[i % rowLength, i / rowLength] = arr[i]; } return output; } Now, when I do the checking, I get completely and utterly strange results: apparently all pixels are either at values of -1 or 0, and these values are completely independent of the original colours. Just for posterity: here's my checking code: private void Check(object sender, MouseButtonEventArgs e) { Point click = e.GetPosition(worldMap); ChangeNotification(intTest[(int)click.X,(int)click.Y].ToString()); } The result show absolutely no correlation to the path that the WriteableBitmap has rendered into it. The path has a fill of solid white. What the heck is going on? I've tried for hours with no luck. Please, this is the major problem stopping me from submitting my first WP7 app. Any guidance?

    Read the article

  • Using ember-resource with couchdb - how can i save my documents?

    - by Thomas Herrmann
    I am implementing an application using ember.js and couchdb. I choose ember-resource as database access layer because it nicely supports nested JSON documents. Since couchdb uses the attribute _rev for optimistic locking in every document, this attribute has to be updated in my application after saving the data to the couchdb. My idea to implement this is to reload the data right after saving to the database and get the new _rev back with the rest of the document. Here is my code for this: // Since we use CouchDB, we have to make sure that we invalidate and re-fetch // every document right after saving it. CouchDB uses an optimistic locking // scheme based on the attribute "_rev" in the documents, so we reload it in // order to have the correct _rev value. didSave: function() { this._super.apply(this, arguments); this.forceReload(); }, // reload resource after save is done, expire to make reload really do something forceReload: function() { this.expire(); // Everything OK up to this location Ember.run.next(this, function() { this.fetch() // Sub-Document is reset here, and *not* refetched! .fail(function(error) { App.displayError(error); }) .done(function() { App.log("App.Resource.forceReload fetch done, got revision " + self.get('_rev')); }); }); } This works for most cases, but if i have a nested model, the sub-model is replaced with the old version of the data just before the fetch is executed! Interestingly enough, the correct (updated) data is stored in the database and the wrong (old) data is in the memory model after the fetch, although the _rev attribut is correct (as well as all attributes of the main object). Here is a part of my object definition: App.TaskDefinition = App.Resource.define({ url: App.dbPrefix + 'courseware', schema: { id: String, _rev: String, type: String, name: String, comment: String, task: { type: 'App.Task', nested: true } } }); App.Task = App.Resource.define({ schema: { id: String, title: String, description: String, startImmediate: Boolean, holdOnComment: Boolean, ..... // other attributes and sub-objects } }); Any ideas where the problem might be? Thank's a lot for any suggestion! Kind regards, Thomas

    Read the article

  • [Cocoa] Placing an NSTimer in a separate thread

    - by ndg
    I'm trying to setup an NSTimer in a separate thread so that it continues to fire when users interact with the UI of my application. This seems to work, but Leaks reports a number of issues - and I believe I've narrowed it down to my timer code. Currently what's happening is that updateTimer tries to access an NSArrayController (timersController) which is bound to an NSTableView in my applications interface. From there, I grab the first selected row and alter its timeSpent column. From reading around, I believe what I should be trying to do is execute the updateTimer function on the main thread, rather than in my timers secondary thread. I'm posting here in the hopes that someone with more experience can tell me if that's the only thing I'm doing wrong. Having read Apple's documentation on Threading, I've found it an overwhelmingly large subject area. NSThread *timerThread = [[[NSThread alloc] initWithTarget:self selector:@selector(startTimerThread) object:nil] autorelease]; [timerThread start]; -(void)startTimerThread { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; activeTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimer:) userInfo:nil repeats:YES] retain]; [runLoop run]; [pool release]; } -(void)updateTimer:(NSTimer *)timer { NSArray *selectedTimers = [timersController selectedObjects]; id selectedTimer = [selectedTimers objectAtIndex:0]; NSNumber *currentTimeSpent = [selectedTimer timeSpent]; [selectedTimer setValue:[NSNumber numberWithInt:[currentTimeSpent intValue]+1] forKey:@"timeSpent"]; } -(void)stopTimer { [activeTimer invalidate]; [activeTimer release]; }

    Read the article

  • Moving UIButton around

    - by pbcoder
    I've tried to move a UIButton up and down in a menu. The problem I've got with the following solution is that the timer is not accurate. Sometimes the Button is moved up 122px, sometimes only 120px. How I can fix this? -(IBAction)marketTabClicked:(id)sender { if (marketTabExtended) { NSLog(@"marketTabExtended = YES"); return; } else { if (iPhoneAppsExtended) { timer = [NSTimer scheduledTimerWithTimeInterval:0.005 target: self selector: @selector(animateItemApps) userInfo: nil repeats: YES]; } else { if (homepageExtended) { timer = [NSTimer scheduledTimerWithTimeInterval:0.005 target: self selector: @selector(animateItemHomepage) userInfo: nil repeats: YES]; } else { timer = [NSTimer scheduledTimerWithTimeInterval:0.005 target: self selector: @selector(animateItemMarketing) userInfo: nil repeats: YES]; } } } [self performSelector:@selector(stopTimer) withObject:self afterDelay:0.605]; iPhoneAppsExtended = NO; homepageExtended = NO; marketTabExtended = NO; marketTabExtended = YES; } -(void)animateItemApps { CGPoint movement; movement = CGPointMake(0, -1); homepage.center = CGPointMake(homepage.center.x, homepage.center.y + movement.y); } -(void)animateItemHomepage { CGPoint movement; movement = CGPointMake(0, 1); homepage.center = CGPointMake(homepage.center.x, homepage.center.y + movement.y); //marketTab.center = CGPointMake(marketTab.center.x, marketTab.center.y + movement.y); } -(void)animateItemMarketing { CGPoint movement; movement = CGPointMake(0, -1); //marketTab.center = CGPointMake(marketTab.center.x, marketTab.center.y + movement.y); homepage.center = CGPointMake(homepage.center.x, homepage.center.y + movement.y); } -(void)stopTimer { [timer invalidate]; }

    Read the article

  • Saving NSString to file

    - by Michael Amici
    I am having trouble saving simple website data to file. I believe the sintax is correct, could someone help me? When I run it, it shows that it gets the data, but when i quit and open up the file that it is supposed to save to, nothing is in it. - (BOOL)textFieldShouldReturn:(UITextField *)nextField { [timer invalidate]; startButton.hidden = NO; startButton.enabled = YES; stopButton.enabled = NO; stopButton.hidden = YES; stopLabel.hidden = YES; label.hidden = NO; label.text = @"Press to Activate"; [nextField resignFirstResponder]; NSString *urlString = textField.text; NSData *dataNew = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]; NSUInteger len = [dataNew length]; NSString *stringCompare = [NSString stringWithFormat:@"%i", len]; NSLog(@"%@", stringCompare); NSString *filePath = [[NSBundle mainBundle] pathForResource:@"websiteone" ofType:@"txt"]; if (filePath) { [stringCompare writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL]; NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL]; NSLog(@"Saving... %@", myText); } else { NSLog(@"cant find the file"); } return YES; }

    Read the article

  • How to obtain the panel within a treeview (WPF)

    - by sperling
    How can one obtain the panel that is used within a TreeView? I've read that by default TreeView uses a VirtualizingStackPanel for this. When I look at a TreeView template, all I see is <ItemsPresenter />, which seems to hide the details of what panel is used. Possible solutions: 1) On the treeview instance ("tv"), from code, do this: tv.ItemsPanel. The problem is, this does not return a panel, but an ItemsPanelTemplate ("gets or sets the template that defines the panel that controls the layout of the items"). 2) Make a TreeView template that explicitly replaces <ItemsPresenter /> with your own ItemsControl.ItemsPanel. I am providing a special template anyways, so this is fine in my scenario. Then give a part name to the panel that you place within that template, and from code you can obtain that part (i.e. the panel). The problem with this? see below. (I am using a control named VirtualTreeView which is derived from TreeView, as is seen below): , use following: -- [sorry folks about poor formatting here, this is my first post, I tried 4 spaces for code... doesn't seem to work?] [I stripped out all clutter here for visibility...] The problem with this is: this immediately overrides any TreeView layout mechanism. Actually, you just get a blank screen, even when you have TreeViewItems filling the tree. Well, the reason I want to get a hold of the panel is to take some part in the MeaureOverride, but without going into all of that, I certainly do not want to rewrite the book of how to layout a treeview. I.e., doing this the step #2 way seems to invalidate the point of even using a TreeView in the first place. Sorry if there is some confusion here, thanks for any help you can offer.

    Read the article

  • Is there a workaround for Linux mono's refusal to acknowledge that I have resized the columns of my

    - by fantius
    When I resize a column, it does not redraw the data with the updated alignment. I've tried Invalidating, Refreshing, and a few other things. Nothing has worked. Does anyone know a workaround? I have not tried this in mono for Windows. To see what I mean, drop this control on a form, and run it in mono for Linux: using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; class MyListView : ListView { private readonly List<ListViewItem> items_ = new List<ListViewItem>(); public MyListView() { VirtualMode = true; Columns.Add("Col 1"); Columns.Add("Col 2"); Columns.Add("Col 3"); Add(new ListViewItem(new[] { "a", "b", "c" })); Add(new ListViewItem(new[] { "a", "b", "c" })); Add(new ListViewItem(new[] { "a", "b", "c" })); Add(new ListViewItem(new[] { "a", "b", "c" })); Add(new ListViewItem(new[] { "a", "b", "c" })); } protected override void OnRetrieveVirtualItem(RetrieveVirtualItemEventArgs e) { e.Item = items_[e.ItemIndex]; base.OnRetrieveVirtualItem(e); } public void Add(ListViewItem item) { items_.Add(item); VirtualListSize = items_.Count; } protected override void OnDrawColumnHeader(DrawListViewColumnHeaderEventArgs e) { e.DrawText(); base.OnDrawColumnHeader(e); } protected override void OnDrawSubItem(DrawListViewSubItemEventArgs e) { var text = ((ListViewItem.ListViewSubItem)e.SubItem).Text; using (var brush = new SolidBrush(e.SubItem.ForeColor)) { e.Graphics.DrawString(text, Font, brush, e.Bounds); } base.OnDrawSubItem(e); } protected override void OnColumnWidthChanged(ColumnWidthChangedEventArgs e) { base.OnColumnWidthChanged(e); Invalidate(true); // Nope, that didn't work Refresh(); // Nope, that didn't work } }

    Read the article

  • Why isn't the Cache invalidated after table update using the SqlCacheDependency?

    - by Jason
    I have been trying to get SqlCacheDependency working. I think I have everything set up correctly, but when I update the table, the item in the Cache isn't invalidated. Can you look at my code and see if I am missing anything? I enabled the Service Broker for the Sandbox database. I have placed the following code in the Global.asax file. I also restart IIS to make sure it is called. void Application_Start(object sender, EventArgs e) { SqlDependency.Start(ConfigurationManager.ConnectionStrings["SandboxConnectionString"].ConnectionString); } I have placed this entry in the web.config file: <system.web> <caching> <sqlCacheDependency enabled="true" pollTime="10000"> <databases> <add name="Sandbox" connectionStringName="SandboxConnectionString"/> </databases> </sqlCacheDependency> </caching> </system.web> I call this code to put the item into the cache: protected void CacheDataSetButton_Click(object sender, EventArgs e) { using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["SandboxConnectionString"].ConnectionString)) { using (SqlCommand sqlCommand = new SqlCommand("SELECT PetID, Name, Breed, Age, Sex, Fixed, Microchipped FROM dbo.Pets", sqlConnection)) { using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand)) { DataSet petsDataSet = new DataSet(); sqlDataAdapter.Fill(petsDataSet, "Pets"); SqlCacheDependency petsSqlCacheDependency = new SqlCacheDependency(sqlCommand); Cache.Insert("Pets", petsDataSet, petsSqlCacheDependency, DateTime.Now.AddSeconds(10), Cache.NoSlidingExpiration); } } } } Then I bind the GridView with this code: protected void BindGridViewButton_Click(object sender, EventArgs e) { if (Cache["Pets"] != null) { GridView1.DataSource = Cache["Pets"] as DataSet; GridView1.DataBind(); } } Between attempts to DataBind the GridView, I change the table's values expecting it to invalidate the Cache["Pets"] item, but it seems to stay in the Cache indefinitely.

    Read the article

  • iPhone shooter game bullet physics!

    - by user298261
    Hello, Making a new shooter game here in the vein of "Galaga" (my fav shooter game growing up). Here's the code I have for bullet physics: -(IBAction)shootBullet:(id)sender{ imgBullet.hidden = NO; timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(fireBullet) userInfo:Nil repeats:YES]; } -(void)fireBullet{ imgBullet.center = CGPointMake(imgBullet.center.x + bulletVelocity.x , imgBullet.center.y + bulletVelocity.y); if(imgBullet.center.y <= 0){ imgBullet.hidden = YES; imgBullet.center = self.view.center; [timer invalidate]; } } Anyway, the obvious issue is that once the bullet leaves the screen, its center is being reset, so I'm reusing the same bullet for each press of the "fire" button. Ideally, I would like the user to be able to spam the "fire" button without causing the program to crash. How would I tinker this existing code so that a bullet object would spawn on the button press each time, and then despawn after it exits the screen, or collides with an enemy? Thank you for any assistance you can offer!

    Read the article

  • android: consume key press, bypassing framework processing

    - by user360024
    What I want android to do: when user presses a single key, have the view respond, but do so without opening a text area and displaying the character associated with the key that was pressed, and without requiring that the Enter key be pressed, and without requiring that the user press Esc to make the text area go away. For example, when user presses "u" (and doesn't press Enter), that means "undo the last action", so the controller and model immediately undo the last action, then the view does an invalidate() and user sees that their last action has been undone. In other words the "u" key press should be silently processed, such that the only visual result is that user's last action has been undone. I've implemented OnKeyListener and provided an onKey() method: the class: public class MyGameView extends View implements OnKeyListener{ in the constructor: //2010jun06, phj: With onKey(), helps let this View consume key presses // before the framework gets a chance to consume the key press. setOnKeyListener((View.OnKeyListener)this); the onKey() method: public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_R) { Log.d("BWA", "In onKey received keycode associated with R."); } return true; // meaning the event (key press) has been consumed, so // the framework should not handle this event. } but when user presses "u" key on the emulator keypad, a textarea is opened at the bottom of the screen, the "u" charater is displayed there, and the onKey() method doesn't execute until user presses the Enter key. Is there a way to make android do what I want? Thanks,

    Read the article

  • Runnable to be run every second only runs once in Fragment onCreateView()

    - by jul
    I'm trying to update the time in a TextView with a Runnable supposed to be run every second. The Runnable is started from a Fragment's onCreateView(), but it's only executed once. Anybody can help? Thanks public class MyFragment extends Fragment { Calendar mCalendar; private Runnable mTicker; private Handler mHandler; TextView mClock; String mFormat; private boolean mClockStopped = false; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RelativeLayout view = (RelativeLayout) inflater.inflate(R.layout.meteo_widget, container, false); /* * Clock (from DigitalClock widget source) */ mClock = (TextView) view.findViewById(R.id.clock); mCalendar = Calendar.getInstance(); mHandler = new Handler(); mTicker = new Runnable() { public void run() { if(mClockStopped) return; mCalendar.setTimeInMillis(System.currentTimeMillis()); mClock.setText(DateFormat.format("hh:mm:ss", mCalendar)); mClock.invalidate(); long now = SystemClock.uptimeMillis(); long next = now + (1000 - now % 1000); mHandler.postAtTime(mTicker, next); } }; mTicker.run(); return view; } @Override public void onResume() { super.onResume(); mClockStopped = true; } @Override public void onPause() { mClockStopped = false; super.onPause(); } }

    Read the article

  • Flushing writes in buffer of Memory Controller to DDR device

    - by Rohit
    At some point in my code, I need to push the writes in my code all the way to the DIMM or DDR device. My requirement is to ensure the write reaches the row,ban,column of the DDR device on the DIMM. I need to read what I've written to the main memory. I do not want caching to get me the value. Instead after writing I want to fetch this value from main memory(DIMM's). So far I've been using Intel's x86 instruction wbinvd(write back and invalidate cache). However this means the caches and TLB are flushed. Write-back requests go to the main memory. However, there is a reasonable amount of time this data might reside in the write buffer of the Memory Controller( Intel calls it integrated memory controller or IMC). The Memory Controller might take some more time depending on the algorithm that runs in the Memory Controller to handle writes. Is there a way I force all existing or pending writes in the write buffer of the memory controller to the DRAM devices ?? What I am looking for is something more direct and more low-level than wbinvd. If you could point me to right documents or specs that describe this I would be grateful. Generally, the IMC has a several registers which can be written or read from. From looking at the specs for that for the chipset I could not find anything useful. Thanks for taking the time to read this.

    Read the article

  • Can't get DataGridView to refresh over Linq to SQL (WinForm)

    - by GringoFrenzy
    Very strange situation here: I'm using L2S to populate a DataGridView. Code follows: private void RefreshUserGrid() { var UserQuery = from userRecord in this.DataContext.tblUsers orderby userRecord.DisplayName select userRecord; UsersGridView.DataSource = UserQuery; //I have also tried //this.UserBindingSource.DataSource = UserQuery; //UsersGridView.Datasource = UserBindingSource; UsersGridView.Columns[0].Visible = false; } Whenever I use L2S to Add/Delete records from the database, the GridView refreshes perfectly well. However, if someone is editing the grid and makes a mistake, I want them to be able to hit a refresh button and have their mistakes erased by reloading from the datasource. For the life of me, I can't get it to work. The code I am currently using on my refresh button is this: private void button1_Click(object sender, EventArgs e) { this.DataContext.Refresh(RefreshMode.OverwriteCurrentValues); RefreshUserGrid(); } But the damn GridView remains unaffected. All that happens is the selected row becomes unselected. I have tried .Refresh(), .Invalidate(), I've tried changing the DataSource to NULL and back again (all suggestions from similar posts here)....none of it works. The only time the Grid refreshes is if I restart the app. I must be missing something fundamental, but I'm totally stumped and so are my colleagues. Any ideas? Thanks!

    Read the article

  • Attempting to calculate width of Map Overlays on the fly

    - by Bloudermilk
    Hey all- I am working on an Android app that utilizes the Google Maps API MapView, MapController, MapActivity, and ItemizedOverlay. I am basically trying to recreate certain functionalities of the Maps app (damn Google for not providing speech bubbles—for lack of a better name—for items!), particularly those speech bubbles. I have an invisible XML structure for the speech bubble in the XML layout file containing my MapView. The first time I show a speech bubble I grab that XML and remove it from it's current parent, applying some ItemizedOverlay.LayoutParams to it, and add it to the MapView as an Overlay. I position it above the item that was selected, fill it with the proper text, then set it to visible. This all works great. The goal here, though, is to also automatically animate the map to reveal any parts of a speech bubble that may be off-screen when it opens. So I'm trying popup.getWidth() (popup is the instance of my LinearLayout that is the speech bubble) after I do all the manipulation to the bubble, even after I display it to the user. Problem is, popup.getWidth() is returning me the width of the previously displayed popup, not the currently displayed one. I can't figure out why this would be happening if I'm fetching the width after I set it to visible with its new dimensions (which, by the way, are relative when I'm setting them with LayoutParams: fill_content for both width and height).. I have even tried forcing both the MapView and the "popup" to invalidate() before trying to fetch the width. Any ideas why this may be happening? How can I force the View to settle into its new dimensions before trying to fetch them? Thanks! Nick

    Read the article

  • Accessing Instance Variables from NSTimer selector

    - by Timbo
    Firstly newbie question: What's the difference between a selector and a method? Secondly newbie question (who would have thought): I need to loop some code based on instance variables and pause between loops until some condition (of course based on instance variables) is met. I've looked at sleep, I've looked at NSThread. In both discussions working through those options many asked why don't I use NSTimer, so here I am. Ok so it's simple enough to get a method (selector? ) to fire on a schedule. Problem I have is that I don't know how to see instance variables I've set up outside the timer from within the code NSTimer fires. I need to see those variables from the NSTimer selector code as I 1) will be updating their values and 2) will set labels based on those values. Here's some code that shows the concept… eventually I'd invalidate the timers based on myVariable too, however I've excluded that for code clarity. MyClass *aMyClassInstance = [MyClass new]; [aMyClassInstance setMyVariable:0]; [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(doStuff) userInfo:nil repeats:YES]; [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(doSomeOtherStuff) userInfo:nil repeats:YES]; - (void) doStuff { [aMyClassInstance setMyVariable:11]; // don't actually have access to set aMyClassInstance.myVariable [self updateSomeUILabel:[NSNumber numberWithInt:aMyClassInstance.myVariable]]; // don't actually have access to aMyClassInstance.myVariable } - (void) doSomeOtherStuff { [aMyClassInstance setMyVariable:22]; // don't actually have access to set aMyClassInstance.myVariable [self updateSomeUILabel:[NSNumber numberWithInt:aMyClassInstance.myVariable]]; // don't actually have access to aMyClassInstance.myVariable } - (void) updateSomeUILabel:(NSNumber *)arg{ int value = [arg intValue]; someUILabel.text = [NSString stringWithFormat:@"myVariable = %d", value]; // Updates the UI with new instance variable values }

    Read the article

  • Making a visual bar timer for iPhone

    - by Ohmnastrum
    I've looked up all results for progress bars and changing the width of an image but it only refers to scaling, and the progress bars aren't customizable so that they fit other functions or design schemes... unless I missed that part. I'm trying to make a bar timer that crops off of the right over a period of time. I tried using an NStimer so that it would subtract from a value each time its function is called. the Timerbar function gets called as a result of another timer invalidating and it works. What doesn't work is that the width isn't changing just the position. further more I keep getting values like Inf and 0 for power and pwrBarWidth I was sure that the changes would occur when Mult was plugged into the equation. it seems like casting mult as an int is causing problems but i'm not sure exactly how. int pwrBarMaxWidth = 137; int pwrBarWidth 0; int limit = 1; float mult; float power = 0; -(void) Timerbar:(NSTimer *)barTimer { if(!waitForPlayer) { [barTimer invalidate]; } if(mult > 0.0) { mult -= 0.001 * [colorChoices count]; if(mult < 0.0) { mult = 0.0; } } power = (mult * 10) / pwrBarMaxWidth; pwrBarWidth = (int)power % limit; // causes the bar to repeat after it reaches a certain point //At this point however the variable Power is always "inf" and PwrBarWidth is always 0. [powerBar setBounds:CGRectMake(powerBar.frame.origin.x, powerBar.frame.origin.y,pwrBarWidth,20)]; //supposed to change the crop of the bar } Any reason why I'm getting inf as a value for power, 0 as a value for pwrBarWidth, and the bar itself isn't cropping? if this question is a bit vague i'll provide more information as needed.

    Read the article

  • Stable/repeatable random sort (MySQL, Rails)

    - by Matt Rogish
    I'd like to paginate through a randomly sorted list of ActiveRecord models (rows from MySQL database). However, this randomization needs to persist on a per-session basis, so that other people that visit the website also receive a random, paginate-able list of records. Let's say there are enough entities (tens of thousands) that storing the randomly sorted ID values in either the session or a cookie is too large, so I must temporarily persist it in some other way (MySQL, file, etc.). Initially I thought I could create a function based on the session ID and the page ID (returning the object IDs for that page) however since the object ID values in MySQL are not sequential (there are gaps), that seemed to fall apart as I was poking at it. The nice thing is that it would require no/minimal storage but the downsides are that it is likely pretty complex to implement and probably CPU intensive. My feeling is I should create an intersection table, something like: random_sorts( sort_id, created_at, user_id NULL if guest) random_sort_items( sort_id, item_id, position ) And then simply store the 'sort_id' in the session. Then, I can paginate the random_sorts WHERE sort_id = n ORDER BY position LIMIT... as usual. Of course, I'd have to put some sort of a reaper in there to remove them after some period of inactivity (based on random_sorts.created_at). Unfortunately, I'd have to invalidate the sort as new objects were created (and/or old objects being removed, although deletion is very rare). And, as load increases the size/performance of this table (even properly indexed) drops. It seems like this ought to be a solved problem but I can't find any rails plugins that do this... Any ideas? Thanks!!

    Read the article

  • Connect 4 C# (How to draw the grid)

    - by Matt Wilde
    I've worked out most of the code and have several game classes. The one bit I'm stuck on at the moment, it how to draw the actual Connect 4 grid. Can anyone tell me what's wrong with this for loop? I get no errors but the grid doesn't appear. I'm using C#. private void Drawgrid() { Brush b = Brushes.Black; Pen p = Pens.Black; for (int xCoor = XStart, col = 0; xCoor < XStart + ColMax * DiscSpace; xCoor += DiscSpace, col++) // x coordinate beginning; while the x coordinate is smaller than the max column size, times it by // the space between each disc and then add the x coord to the disc space in order to create a new circle. for (int yCoor = YStart, row = RowMax - 1; yCoor < YStart + RowMax * DiscScale; yCoor += DiscScale, row--) { switch (Grid.State[row, col]) { case GameGrid.Gridvalues.Red: b = Brushes.Red; break; case GameGrid.Gridvalues.Yellow: b = Brushes.Yellow; break; case GameGrid.Gridvalues.None: b = Brushes.Aqua; break; } MainDisplay.DrawEllipse(p, xCoor, yCoor, 50, 50); MainDisplay.FillEllipse(b, xCoor, yCoor, 50, 50); } Invalidate(); } Thanks.

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13  | Next Page >