Search Results

Search found 21054 results on 843 pages for 'the void'.

Page 18/843 | < Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >

  • UITableView not displaying parsed data

    - by Graeme
    I have a UITableView which is setup in Interface Builder and connected properly to its class in Xcode. I also have a "Importer" Class which downloads and parses an RSS feed and stores the information in an NSMutableArray. However I have verified the parsing is working properly (using breakpoints and NSlog) but no data is showing in the UITable View. Any ideas as to what the problem could be? I'm almost out of them. It's based on the XML performance Apple example. Here's the code for TableView.h: #import <UIKit/UIKit.h> #import "IncidentsImporter.h" @class SongDetailsController; @interface CurrentIncidentsTableViewController : UITableViewController <IncidentsImporterDelegate>{ NSMutableArray *incidents; SongDetailsController *detailController; UITableView *ctableView; IncidentsImporter *parser; } @property (nonatomic, retain) NSMutableArray *incidents; @property (nonatomic, retain, readonly) SongDetailsController *detailController; @property (nonatomic, retain) IncidentsImporter *parser; @property (nonatomic, retain) IBOutlet UITableView *ctableView; // Called by the ParserChoiceViewController based on the selected parser type. - (void)beginParsing; @end And the code for .m: #import "CurrentIncidentsTableViewController.h" #import "SongDetailsController.h" #import "Incident.h" @implementation CurrentIncidentsTableViewController @synthesize ctableView, incidents, parser, detailController; #pragma mark - #pragma mark View lifecycle - (void)viewDidLoad { [super viewDidLoad]; self.parser = [[IncidentsImporter alloc] init]; parser.delegate = self; [parser start]; UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(beginParsing)]; self.navigationItem.rightBarButtonItem = refreshButton; [refreshButton release]; // Uncomment the following line to preserve selection between presentations. //self.clearsSelectionOnViewWillAppear = NO; // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem; } - (void)viewWillAppear:(BOOL)animated { NSIndexPath *selectedRowIndexPath = [ctableView indexPathForSelectedRow]; if (selectedRowIndexPath != nil) { [ctableView deselectRowAtIndexPath:selectedRowIndexPath animated:NO]; } } // This method will be called repeatedly - once each time the user choses to parse. - (void)beginParsing { NSLog(@"Parsing has begun"); //self.navigationItem.rightBarButtonItem.enabled = NO; // Allocate the array for song storage, or empty the results of previous parses if (incidents == nil) { NSLog(@"Grabbing array"); self.incidents = [NSMutableArray array]; } else { [incidents removeAllObjects]; [ctableView reloadData]; } // Create the parser, set its delegate, and start it. self.parser = [[IncidentsImporter alloc] init]; parser.delegate = self; [parser start]; } /* - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } */ /* - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } */ /* - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } */ - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Override to allow orientations other than the default portrait orientation. return YES; } #pragma mark - #pragma mark Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [incidents count]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"Table Cell Sought"); static NSString *kCellIdentifier = @"MyCell"; UITableViewCell *cell = [ctableView dequeueReusableCellWithIdentifier:kCellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier] autorelease]; cell.textLabel.font = [UIFont boldSystemFontOfSize:14.0]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; } cell.textLabel.text = @"Test";//[[incidents objectAtIndex:indexPath.row] title]; return cell; } /* // Override to support conditional editing of the table view. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } */ /* // Override to support editing the table view. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { } */ /* // Override to support conditional rearranging of the table view. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the item to be re-orderable. return YES; } */ #pragma mark - #pragma mark Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { self.detailController.incident = [incidents objectAtIndex:indexPath.row]; [self.navigationController pushViewController:self.detailController animated:YES]; } #pragma mark - #pragma mark Memory management - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Relinquish ownership any cached data, images, etc that aren't in use. } - (void)viewDidUnload { // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. // For example: self.myOutlet = nil; } - (void)parserDidEndParsingData:(IncidentsImporter *)parser { [ctableView reloadData]; self.navigationItem.rightBarButtonItem.enabled = YES; self.parser = nil; } - (void)parser:(IncidentsImporter *)parser didParseIncidents:(NSArray *)parsedIncidents { //[incidents addObjectsFromArray: parsedIncidents]; // Three scroll view properties are checked to keep the user interface smooth during parse. When new objects are delivered by the parser, the table view is reloaded to display them. If the table is reloaded while the user is scrolling, this can result in eratic behavior. dragging, tracking, and decelerating can be checked for this purpose. When the parser finishes, reloadData will be called in parserDidEndParsingData:, guaranteeing that all data will ultimately be displayed even if reloadData is not called in this method because of user interaction. if (!ctableView.dragging && !ctableView.tracking && !ctableView.decelerating) { self.title = [NSString stringWithFormat:NSLocalizedString(@"Top %d Songs", @"Top Songs format"), [parsedIncidents count]]; [ctableView reloadData]; } } - (void)parser:(IncidentsImporter *)parser didFailWithError:(NSError *)error { // handle errors as appropriate to your application... } - (void)dealloc { [super dealloc]; } @end

    Read the article

  • C++ 2d Array Class Function Call Help

    - by johnny-conrad
    I hope this question takes a simple fix, and I am just missing something very small. I am in my second semester of C++ in college, and we are just getting into OOP. This is my first OOP program, and it is causing me a little problem. Here are the errors I am getting: Member function must be called or its address taken in function displayGrid(int,Cell ( *)[20]) Member function must be called or its address taken in function Turn(int,int,Cell ( *)[20]) Member function must be called or its address taken in function Turn(int,int,Cell ( *)[20]) Warning: Parameter 'grid' is never used in function displayGrid(int,Cell ( *)[20]) Here is all of my code. I am aware It is much more code than necessary, sorry if it makes it more difficult. I was worried that I might accidentally delete something. const int MAX=20; //Struct Cell holds player and their symbol. class Cell { private: int Player; char Symbol; public: Cell(void); void setPlayer(int); void setSymbol(char); int getPlayer(void); char getSymbol(void); }; Cell::Cell(void) { Symbol ='-'; } void Cell::setPlayer(int player_num) { Player = player_num; } void Cell::setSymbol(char rps) { Symbol = rps; } int Cell::getPlayer(void) { return Player; } char Cell::getSymbol(void) { return Symbol; } void Turn(int, int, Cell[MAX][MAX]); void displayGrid(int, Cell[MAX][MAX]); void main(void) { int size; cout << "How big would you like the grid to be: "; cin >> size; //Checks to see valid grid size while(size>MAX || size<3) { cout << "Grid size must between 20 and 3." << endl; cout << "Please re-enter the grid size: "; cin >> size; } int cnt=1; int full; Cell grid[MAX][MAX]; //I use full to detect when the game is over by squaring size. full = size*size; cout << "Starting a new game." << endl; //Exits loop when cnt reaches full. while(cnt<full+1) { displayGrid(size, grid); //calls function to display grid if(cnt%2==0) //if cnt is even then it's 2nd players turn cout << "Player 2's turn." << endl; else cout << "Player 1's turn" << endl; Turn(size, cnt, grid); //calls Turn do each players turn cnt++; } cout << endl; cout << "Board is full... Game Over" << endl; } void displayGrid(int size, Cell grid[MAX][MAX]) { cout << endl; cout << " "; for(int x=1; x<size+1; x++) // prints first row cout << setw(3) << x; // of numbers. cout << endl; //Nested-For prints the grid. for(int i=1; i<size+1; i++) { cout << setw(2) << i; for(int c=1; c<size+1; c++) { cout << setw(3) << grid[i][c].getSymbol; } cout << endl; } cout << endl; } void Turn(int size, int cnt, Cell grid[MAX][MAX]) { char temp; char choice; int row=0; int column=0; cout << "Enter the Row: "; cin >> row; cout << "Enter the Column: "; cin >> column; //puts what is in the current cell in "temp" temp = grid[row][column].getSymbol; //Checks to see if temp is occupied or not while(temp!='-') { cout << "Cell space is Occupied..." << endl; cout << "Enter the Row: "; cin >> row; cout << "Enter the Column: "; cin >> column; temp = grid[row][column].getSymbol; //exits loop when finally correct } if(cnt%2==0) //if cnt is even then its player 2's turn { cout << "Enter your Symbol R, P, or S (Capitals): "; cin >> choice; grid[row][column].setPlayer(1); in >> choice; } //officially sets choice to grid cell grid[row][column].setSymbol(choice); } else //if cnt is odd then its player 1's turn { cout << "Enter your Symbol r, p, or s (Lower-Case): "; cin >> choice; grid[row][column].setPlayer(2); //checks for valid input by user1 while(choice!= 'r' && choice!='p' && choice!='s') { cout << "Invalid Symbol... Please Re-Enter: "; cin >> choice; } //officially sets choice to grid cell. grid[row][column].setSymbol(choice); } cout << endl; } Thanks alot for your help!

    Read the article

  • Can't figure out where race condition is occuring

    - by Nik
    I'm using Valgrind --tool=drd to check my application that uses Boost::thread. Basically, the application populates a set of "Book" values with "Kehai" values based on inputs through a socket connection. On a seperate thread, a user can connect and get the books send to them. Its fairly simple, so i figured using a boost::mutex::scoped_lock on the location that serializes the book and the location that clears out the book data should be suffice to prevent any race conditions. Here is the code: void Book::clear() { boost::mutex::scoped_lock lock(dataMutex); for(int i =NUM_KEHAI-1; i >= 0; --i) { bid[i].clear(); ask[i].clear(); } } int Book::copyChangedKehaiToString(char* dst) const { boost::mutex::scoped_lock lock(dataMutex); sprintf(dst, "%-4s%-13s",market.c_str(),meigara.c_str()); int loc = 17; for(int i = 0; i < Book::NUM_KEHAI; ++i) { if(ask[i].changed > 0) { sprintf(dst+loc,"A%i%-21s%-21s%-21s%-8s%-4s",i,ask[i].price.c_str(),ask[i].volume.c_str(),ask[i].number.c_str(),ask[i].postTime.c_str(),ask[i].status.c_str()); loc += 77; } } for(int i = 0; i < Book::NUM_KEHAI; ++i) { if(bid[i].changed > 0) { sprintf(dst+loc,"B%i%-21s%-21s%-21s%-8s%-4s",i,bid[i].price.c_str(),bid[i].volume.c_str(),bid[i].number.c_str(),bid[i].postTime.c_str(),bid[i].status.c_str()); loc += 77; } } return loc; } The clear() function and the copyChangedKehaiToString() function are called in the datagetting thread and data sending thread,respectively. Also, as a note, the class Book: struct Book { private: Book(const Book&); Book& operator=(const Book&); public: static const int NUM_KEHAI=10; struct Kehai; friend struct Book::Kehai; struct Kehai { private: Kehai& operator=(const Kehai&); public: std::string price; std::string volume; std::string number; std::string postTime; std::string status; int changed; Kehai(); void copyFrom(const Kehai& other); Kehai(const Kehai& other); inline void clear() { price.assign(""); volume.assign(""); number.assign(""); postTime.assign(""); status.assign(""); changed = -1; } }; std::vector<Kehai> bid; std::vector<Kehai> ask; tm recTime; mutable boost::mutex dataMutex; Book(); void clear(); int copyChangedKehaiToString(char * dst) const; }; When using valgrind --tool=drd, i get race condition errors such as the one below: ==26330== Conflicting store by thread 1 at 0x0658fbb0 size 4 ==26330== at 0x653AE68: std::string::_M_mutate(unsigned int, unsigned int, unsigned int) (in /usr/lib/libstdc++.so.6.0.8) ==26330== by 0x653AFC9: std::string::_M_replace_safe(unsigned int, unsigned int, char const*, unsigned int) (in /usr/lib/libstdc++.so.6.0.8) ==26330== by 0x653B064: std::string::assign(char const*, unsigned int) (in /usr/lib/libstdc++.so.6.0.8) ==26330== by 0x653B134: std::string::assign(char const*) (in /usr/lib/libstdc++.so.6.0.8) ==26330== by 0x8055D64: Book::Kehai::clear() (Book.h:50) ==26330== by 0x8094A29: Book::clear() (Book.cpp:78) ==26330== by 0x808537E: RealKernel::start() (RealKernel.cpp:86) ==26330== by 0x804D15A: main (main.cpp:164) ==26330== Allocation context: BSS section of /usr/lib/libstdc++.so.6.0.8 ==26330== Other segment start (thread 2) ==26330== at 0x400BB59: pthread_mutex_unlock (drd_pthread_intercepts.c:633) ==26330== by 0xC59565: pthread_mutex_unlock (in /lib/libc-2.5.so) ==26330== by 0x805477C: boost::mutex::unlock() (mutex.hpp:56) ==26330== by 0x80547C9: boost::unique_lock<boost::mutex>::~unique_lock() (locks.hpp:340) ==26330== by 0x80949BA: Book::copyChangedKehaiToString(char*) const (Book.cpp:134) ==26330== by 0x80937EE: BookSerializer::serializeBook(Book const&, std::string const&) (BookSerializer.cpp:41) ==26330== by 0x8092D05: BookSnapshotManager::getSnaphotDataList() (BookSnapshotManager.cpp:72) ==26330== by 0x8088179: SnapshotServer::getDataList() (SnapshotServer.cpp:246) ==26330== by 0x808870F: SnapshotServer::run() (SnapshotServer.cpp:183) ==26330== by 0x808BAF5: boost::_mfi::mf0<void, RealThread>::operator()(RealThread*) const (mem_fn_template.hpp:49) ==26330== by 0x808BB4D: void boost::_bi::list1<boost::_bi::value<RealThread*> >::operator()<boost::_mfi::mf0<void, RealThread>, boost::_bi::list0>(boost::_bi::type<void>, boost::_mfi::mf0<void, RealThread>&, boost::_bi::list0&, int) (bind.hpp:253) ==26330== by 0x808BB90: boost::_bi::bind_t<void, boost::_mfi::mf0<void, RealThread>, boost::_bi::list1<boost::_bi::value<RealThread*> > >::operator()() (bind_template.hpp:20) ==26330== Other segment end (thread 2) ==26330== at 0x400B62A: pthread_mutex_lock (drd_pthread_intercepts.c:580) ==26330== by 0xC59535: pthread_mutex_lock (in /lib/libc-2.5.so) ==26330== by 0x80546B8: boost::mutex::lock() (mutex.hpp:51) ==26330== by 0x805473B: boost::unique_lock<boost::mutex>::lock() (locks.hpp:349) ==26330== by 0x8054769: boost::unique_lock<boost::mutex>::unique_lock(boost::mutex&) (locks.hpp:227) ==26330== by 0x8094711: Book::copyChangedKehaiToString(char*) const (Book.cpp:113) ==26330== by 0x80937EE: BookSerializer::serializeBook(Book const&, std::string const&) (BookSerializer.cpp:41) ==26330== by 0x808870F: SnapshotServer::run() (SnapshotServer.cpp:183) ==26330== by 0x808BAF5: boost::_mfi::mf0<void, RealThread>::operator()(RealThread*) const (mem_fn_template.hpp:49) ==26330== by 0x808BB4D: void boost::_bi::list1<boost::_bi::value<RealThread*> >::operator()<boost::_mfi::mf0<void, RealThread>, boost::_bi::list0>(boost::_bi::type<void>, boost::_mfi::mf0<void, RealThread>&, boost::_bi::list0&, int) (bind.hpp:253) For the life of me, i can't figure out where the race condition is. As far as I can tell, clearing the kehai is done only after having taken the mutex, and the same holds true with copying it to a string. Does anyone have any ideas what could be causing this, or where I should look? Thank you kindly.

    Read the article

  • struct to bidimensional struct pointer assigment in C

    - by argos.void
    i want to get work this code and i googled and asked in efnet and freenode but i didnt find the answer. what i want i to assign a struct woot to an another bidimensional struct woot *, and i need malloc to do that. then, how can i use malloc there and how to assign the struct? thanks. #include <stdio.h> struct omg { int foo; }; struct woot { struct omg *localfoo; int foo; }; int a = sizeof(struct woot); int main(void){ struct woot *what[10][10] = (struct woot *) malloc(100*a); struct omg hahaha[100]; hahaha[1].foo = 15; what[1][6].localfoo = &hahaha[1]; }

    Read the article

  • GSL-GNU in Visual studio

    - by Arman
    I have visual studio 2008, I want to integrate GSL library in my project, kindly give me some guidelines so that I can make it possible. I have added the GSL library but the following error come. Error 1 error LNK2028: unresolved token (0A000010) "extern "C" void __cdecl gsl_matrix_set(struct gsl_matrix *,unsigned int,unsigned int,double)" (?gsl_matrix_set@@$$J0YAXPAUgsl_matrix@@IIN@Z) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ) Error 2 error LNK2028: unresolved token (0A000011) "extern "C" struct gsl_matrix * __cdecl gsl_matrix_alloc(unsigned int,unsigned int)" (?gsl_matrix_alloc@@$$J0YAPAUgsl_matrix@@II@Z) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ) Error 3 error LNK2028: unresolved token (0A000014) "extern "C" double __cdecl gsl_matrix_get(struct gsl_matrix const *,unsigned int,unsigned int)" (?gsl_matrix_get@@$$J0YANPBUgsl_matrix@@II@Z) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ) Error 4 error LNK2019: unresolved external symbol "extern "C" double __cdecl gsl_matrix_get(struct gsl_matrix const *,unsigned int,unsigned int)" (?gsl_matrix_get@@$$J0YANPBUgsl_matrix@@II@Z) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ) Error 5 error LNK2019: unresolved external symbol "extern "C" void __cdecl gsl_matrix_set(struct gsl_matrix *,unsigned int,unsigned int,double)" (?gsl_matrix_set@@$$J0YAXPAUgsl_matrix@@IIN@Z) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ)

    Read the article

  • BlackBerry/J2ME - SAX parse collection of objects with attributes

    - by Changqi Guo
    I have a problem with using the SAX parser to parse a XML file. It is a complex XML file, it is like the following. <Objects> <Object no="1"> <field name="PID">ilives:87877</field> <field name="dc.coverage">Charlottetown</field> <field name="fgs.ownerId">fedoraAdmin</field> </Object> <Object no="2">...... I am confused how to get the names in each field, and how to store the information of each object. import java.util.Enumeration; import java.util.Hashtable; public class XMLObject { private Hashtable mFields = new Hashtable(); private int mN = -1; public int getN() { return mN; } public void setN(int n) { mN = n; } public String getStringField(String key) { return (String) mFields.get(key); } public void setStringField(String key, String value) { mFields.put(key, value); } public String getPID() { return getStringField("PID"); } public void setPID(String pid) { setStringField("PID", pid); } public String getDcCoverage() { return getStringField("dc.coverage"); } public void setDcCoverage(String dcCoverage) { setStringField("dc.coverage", dcCoverage); } public String getFgsOwnerId() { return getStringField("fgs.ownerId"); } public void setFgsOwnerId(String fgsOwnerId) { setStringField("fgs.ownerId", fgsOwnerId); } public String dccreator() { return getStringField("dc.creator"); } public void dccreator(String dccreator) { setStringField("dc.creator", dccreator); } public String getdcformat() { return getStringField("dc.format"); } public void setdcformat(String dcformat) { setStringField("dc.format", dcformat); } public String getdcidentifier() { return getStringField("dc.identifier"); } public void setdcidentifier(String dcidentifier) { setStringField("dc.identifier", dcidentifier); } public String getdclanguage() { return getStringField("dc.language"); } public void setdclanguage(String dclanguage) { setStringField("dc.language", dclanguage); } public String getdcpublisher() { return getStringField("dc.publisher"); } public void setdcpublisher(String dcpublisher) { setStringField("dc.publisher",dcpublisher); } public String getdcsubject() { return getStringField("dc.subject"); } public void setdcsubject(String dcsubject) { setStringField("dc.subject",dcsubject); } public String getdctitle() { return getStringField("dc.title"); } public void setdctitle(String dctitle) { setStringField("dc.title",dctitle); } public String getdctype() { return getStringField("dc.type"); } public void setdctype(String dctype) { setStringField("dc.type",dctype); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("N:"+mN+";"); Enumeration keys = mFields.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); sb.append(key+":"+mFields.get(key)+";"); } return sb.toString(); } } i used the same handler class you provided import java.io.*; import net.rim.device.api.system.Bitmap; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.InputStream; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.MainScreen; import net.rim.device.api.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.*; import org.xml.sax.helpers.DefaultHandler; public class xmlparsermainscreen extends MainScreen{ private static String xmlres = "/xml/xml1.xml"; private RichTextField textOutputField; public xmlparsermainscreen() throws ParserConfigurationException, net.rim.device.api.xml.parsers.ParserConfigurationException, IOException { InputStream inputStream = getClass().getResourceAsStream(xmlres); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[10000]; int bytesRead = inputStream.read(buffer); while (bytesRead > 0) { baos.write(buffer, 0, bytesRead); bytesRead = inputStream.read(buffer); } baos.close(); String result=baos.toString(); ByteArrayInputStream bais = new ByteArrayInputStream(result.getBytes()); XMLObject[] xmlObjects = getXMLObjects(bais); for (int i = 0; i < xmlObjects.length; i++) { XMLObject o = xmlObjects[i]; textOutputField = new RichTextField(); add(textOutputField); textOutputField.setText(o.toString()); // add(new LabelField(o.toString())); } LabelField resultdis=new LabelField("resultdisplay"); add(resultdis); //textOutputField = new RichTextField(); //add(textOutputField); //textOutputField.setText(result); } static XMLObject[] getXMLObjects(InputStream is) throws ParserConfigurationException { XMLObjectHandler xmlObjectHandler = new XMLObjectHandler(); try { SAXParser parser = SAXParserFactory.newInstance() .newSAXParser(); parser.parse(is, xmlObjectHandler); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return xmlObjectHandler.getXMLObjects(); } } import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import net.rim.device.api.ui.UiApplication; public class xmlparser extends UiApplication { private xmlparser() throws ParserConfigurationException, net.rim.device.api.xml.parsers.ParserConfigurationException, IOException { pushScreen( new xmlparsermainscreen() ); } public static void main( String[] args ) throws ParserConfigurationException, net.rim.device.api.xml.parsers.ParserConfigurationException, IOException { new xmlparser().enterEventDispatcher(); } }

    Read the article

  • JPanel Layout Image Cutoff

    - by Trizicus
    I am adding images to a JPanel but the images are getting cut off. I was originally trying BorderLayout but that only worked for one image and adding others added image cut-off. So I switched to other layouts and the best and closest I could get was BoxLayout however that adds a very large cut-off which is not acceptable either. So basically; How can I add images (from a custom JComponent) to a custom JPanel without bad effects such as the one present in the code. Custom JPanel: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.Timer; public class GraphicsPanel extends JPanel implements MouseListener { private Entity test; private Timer timer; private long startTime = 0; private int numFrames = 0; private float fps = 0.0f; GraphicsPanel() { test = new Entity("test.png"); Thread t1 = new Thread(test); t1.start(); Entity ent2 = new Entity("images.jpg"); ent2.setX(150); ent2.setY(150); Thread t2 = new Thread(ent2); t2.start(); Entity ent3 = new Entity("test.png"); ent3.setX(0); ent3.setY(150); Thread t3 = new Thread(ent3); t3.start(); //ESSENTIAL setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); add(test); add(ent2); add(ent3); //GAMELOOP timer = new Timer(30, new Gameloop(this)); timer.start(); addMouseListener(this); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g.create(); g2.setClip(0, 0, getWidth(), getHeight()); g2.setColor(Color.BLACK); g2.drawString("FPS: " + fps, 1, 15); } public void getFPS() { ++numFrames; if (startTime == 0) { startTime = System.currentTimeMillis(); } else { long currentTime = System.currentTimeMillis(); long delta = (currentTime - startTime); if (delta > 1000) { fps = (numFrames * 1000) / delta; numFrames = 0; startTime = currentTime; } } } public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } class Gameloop implements ActionListener { private GraphicsPanel gp; Gameloop(GraphicsPanel gp) { this.gp = gp; } public void actionPerformed(ActionEvent e) { try { gp.getFPS(); gp.repaint(); } catch (Exception ez) { } } } } Main class: import java.awt.EventQueue; import javax.swing.JFrame; public class MainWindow { public static void main(String[] args) { new MainWindow(); } private JFrame frame; private GraphicsPanel gp = new GraphicsPanel(); MainWindow() { EventQueue.invokeLater(new Runnable() { public void run() { frame = new JFrame("Graphics Practice"); frame.setSize(680, 420); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(gp); } }); } } Custom JComponent import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import javax.swing.JComponent; public class Entity extends JComponent implements Runnable { private BufferedImage bImg; private int x = 0; private int y = 0; private int entityWidth, entityHeight; private String filename; Entity(String filename) { this.filename = filename; } public void run() { bImg = loadBImage(filename); entityWidth = bImg.getWidth(); entityHeight = bImg.getHeight(); setPreferredSize(new Dimension(entityWidth, entityHeight)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.drawImage(bImg, x, y, null); g2d.dispose(); } public BufferedImage loadBImage(String filename) { try { bImg = ImageIO.read(getClass().getResource(filename)); } catch (Exception e) { } return bImg; } public int getEntityWidth() { return entityWidth; } public int getEntityHeight() { return entityHeight; } public int getX() { return x; } public int getY() { return y; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } }

    Read the article

  • NullPointerException when linking to Service that uses ContentProvider

    - by Danny Chia
    H.i everyone, this is my first post here! Anyways, I'm trying to write a "todo list" application. It stores the data in a ContentProvider, which is accessed via a Service. However, my app crashes at launch. My code is below: Manifest file: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.examples.todolist" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="True"> <activity android:name=".ToDoList" android:label="@string/app_name" android:theme="@style/ToDoTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name="TodoService"/> <provider android:name="TodoProvider" android:authorities="com.examples.provider.todolist" /> </application> <uses-sdk android:minSdkVersion="7" /> </manifest> ToDoList.java: package com.examples.todolist; import com.examples.todolist.TodoService.LocalBinder; import java.util.ArrayList; import java.util.Date; import android.app.Activity; import android.content.SharedPreferences; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.view.ContextMenu; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnKeyListener; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; public class ToDoList extends Activity { static final private int ADD_NEW_TODO = Menu.FIRST; static final private int REMOVE_TODO = Menu.FIRST + 1; private static final String TEXT_ENTRY_KEY = "TEXT_ENTRY_KEY"; private static final String ADDING_ITEM_KEY = "ADDING_ITEM_KEY"; private static final String SELECTED_INDEX_KEY = "SELECTED_INDEX_KEY"; private boolean addingNew = false; private ArrayList<ToDoItem> todoItems; private ListView myListView; private EditText myEditText; private ToDoItemAdapter aa; int entries = 0; int notifs = 0; //ToDoDBAdapter toDoDBAdapter; Cursor toDoListCursor; TodoService mService; boolean mBound = false; /** Called when the activity is first created. */ public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); myListView = (ListView)findViewById(R.id.myListView); myEditText = (EditText)findViewById(R.id.myEditText); todoItems = new ArrayList<ToDoItem>(); int resID = R.layout.todolist_item; aa = new ToDoItemAdapter(this, resID, todoItems); myListView.setAdapter(aa); myEditText.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { ToDoItem newItem = new ToDoItem(myEditText.getText().toString(), 0); mService.insertTask(newItem); updateArray(); myEditText.setText(""); entries++; Toast.makeText(ToDoList.this, "Entry added", Toast.LENGTH_SHORT).show(); aa.notifyDataSetChanged(); cancelAdd(); return true; } return false; } }); registerForContextMenu(myListView); restoreUIState(); populateTodoList(); } private void populateTodoList() { // Get all the todo list items from the database. toDoListCursor = mService. getAllToDoItemsCursor(); startManagingCursor(toDoListCursor); // Update the array. updateArray(); Toast.makeText(this, "Todo list retrieved", Toast.LENGTH_SHORT).show(); } private void updateArray() { toDoListCursor.requery(); todoItems.clear(); if (toDoListCursor.moveToFirst()) do { String task = toDoListCursor.getString(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_TASK)); long created = toDoListCursor.getLong(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_CREATION_DATE)); int taskid = toDoListCursor.getInt(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_ID)); ToDoItem newItem = new ToDoItem(task, new Date(created), taskid); todoItems.add(0, newItem); } while(toDoListCursor.moveToNext()); aa.notifyDataSetChanged(); } private void restoreUIState() { // Get the activity preferences object. SharedPreferences settings = getPreferences(0); // Read the UI state values, specifying default values. String text = settings.getString(TEXT_ENTRY_KEY, ""); Boolean adding = settings.getBoolean(ADDING_ITEM_KEY, false); // Restore the UI to the previous state. if (adding) { addNewItem(); myEditText.setText(text); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putInt(SELECTED_INDEX_KEY, myListView.getSelectedItemPosition()); super.onSaveInstanceState(outState); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { int pos = -1; if (savedInstanceState != null) if (savedInstanceState.containsKey(SELECTED_INDEX_KEY)) pos = savedInstanceState.getInt(SELECTED_INDEX_KEY, -1); myListView.setSelection(pos); } @Override protected void onPause() { super.onPause(); // Get the activity preferences object. SharedPreferences uiState = getPreferences(0); // Get the preferences editor. SharedPreferences.Editor editor = uiState.edit(); // Add the UI state preference values. editor.putString(TEXT_ENTRY_KEY, myEditText.getText().toString()); editor.putBoolean(ADDING_ITEM_KEY, addingNew); // Commit the preferences. editor.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // Create and add new menu items. MenuItem itemAdd = menu.add(0, ADD_NEW_TODO, Menu.NONE, R.string.add_new); MenuItem itemRem = menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove); // Assign icons itemAdd.setIcon(R.drawable.add_new_item); itemRem.setIcon(R.drawable.remove_item); // Allocate shortcuts to each of them. itemAdd.setShortcut('0', 'a'); itemRem.setShortcut('1', 'r'); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); int idx = myListView.getSelectedItemPosition(); String removeTitle = getString(addingNew ? R.string.cancel : R.string.remove); MenuItem removeItem = menu.findItem(REMOVE_TODO); removeItem.setTitle(removeTitle); removeItem.setVisible(addingNew || idx > -1); return true; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle("Selected To Do Item"); menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove); } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); int index = myListView.getSelectedItemPosition(); switch (item.getItemId()) { case (REMOVE_TODO): { if (addingNew) { cancelAdd(); } else { removeItem(index); } return true; } case (ADD_NEW_TODO): { addNewItem(); return true; } } return false; } @Override public boolean onContextItemSelected(MenuItem item) { super.onContextItemSelected(item); switch (item.getItemId()) { case (REMOVE_TODO): { AdapterView.AdapterContextMenuInfo menuInfo; menuInfo =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); int index = menuInfo.position; removeItem(index); return true; } } return false; } @Override public void onDestroy() { super.onDestroy(); } private void cancelAdd() { addingNew = false; myEditText.setVisibility(View.GONE); } private void addNewItem() { addingNew = true; myEditText.setVisibility(View.VISIBLE); myEditText.requestFocus(); } private void removeItem(int _index) { // Items are added to the listview in reverse order, so invert the index. //toDoDBAdapter.removeTask(todoItems.size()-_index); ToDoItem item = todoItems.get(_index); final long selectedId = item.getTaskId(); mService.removeTask(selectedId); entries--; Toast.makeText(this, "Entry deleted", Toast.LENGTH_SHORT).show(); updateArray(); } @Override protected void onStart() { super.onStart(); Intent intent = new Intent(this, TodoService.class); bindService(intent, mConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); // Unbind from the service if (mBound) { unbindService(mConnection); mBound = false; } } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { LocalBinder binder = (LocalBinder) service; mService = binder.getService(); mBound = true; } public void onServiceDisconnected(ComponentName arg0) { mBound = false; } }; public class TimedToast extends AsyncTask<Long, Integer, Integer> { @Override protected Integer doInBackground(Long... arg0) { if (notifs < 15) { try { Toast.makeText(ToDoList.this, entries + " entries left", Toast.LENGTH_SHORT).show(); notifs++; Thread.sleep(20000); } catch (InterruptedException e) { } } return 0; } } } TodoService.java: package com.examples.todolist; import android.app.Service; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.os.Binder; import android.os.IBinder; public class TodoService extends Service { private final IBinder mBinder = new LocalBinder(); @Override public IBinder onBind(Intent arg0) { return mBinder; } public class LocalBinder extends Binder { TodoService getService() { return TodoService.this; } } public void insertTask(ToDoItem _task) { ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); values.put(TodoProvider.KEY_CREATION_DATE, _task.getCreated().getTime()); values.put(TodoProvider.KEY_TASK, _task.getTask()); cr.insert(TodoProvider.CONTENT_URI, values); } public void updateTask(ToDoItem _task) { long tid = _task.getTaskId(); ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); values.put(TodoProvider.KEY_TASK, _task.getTask()); cr.update(TodoProvider.CONTENT_URI, values, TodoProvider.KEY_ID + "=" + tid, null); } public void removeTask(long tid) { ContentResolver cr = getContentResolver(); cr.delete(TodoProvider.CONTENT_URI, TodoProvider.KEY_ID + "=" + tid, null); } public Cursor getAllToDoItemsCursor() { ContentResolver cr = getContentResolver(); return cr.query(TodoProvider.CONTENT_URI, null, null, null, null); } } TodoProvider.java: package com.examples.todolist; import android.content.*; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.net.Uri; import android.text.TextUtils; import android.util.Log; public class TodoProvider extends ContentProvider { public static final Uri CONTENT_URI = Uri.parse("content://com.examples.provider.todolist/todo"); @Override public boolean onCreate() { Context context = getContext(); todoHelper dbHelper = new todoHelper(context, DATABASE_NAME, null, DATABASE_VERSION); todoDB = dbHelper.getWritableDatabase(); return (todoDB == null) ? false : true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sort) { SQLiteQueryBuilder tb = new SQLiteQueryBuilder(); tb.setTables(TODO_TABLE); // If this is a row query, limit the result set to the passed in row. switch (uriMatcher.match(uri)) { case TASK_ID: tb.appendWhere(KEY_ID + "=" + uri.getPathSegments().get(1)); break; default: break; } // If no sort order is specified sort by date / time String orderBy; if (TextUtils.isEmpty(sort)) { orderBy = KEY_ID; } else { orderBy = sort; } // Apply the query to the underlying database. Cursor c = tb.query(todoDB, projection, selection, selectionArgs, null, null, orderBy); // Register the contexts ContentResolver to be notified if // the cursor result set changes. c.setNotificationUri(getContext().getContentResolver(), uri); // Return a cursor to the query result. return c; } @Override public Uri insert(Uri _uri, ContentValues _initialValues) { // Insert the new row, will return the row number if // successful. long rowID = todoDB.insert(TODO_TABLE, "task", _initialValues); // Return a URI to the newly inserted row on success. if (rowID > 0) { Uri uri = ContentUris.withAppendedId(CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(uri, null); return uri; } throw new SQLException("Failed to insert row into " + _uri); } @Override public int delete(Uri uri, String where, String[] whereArgs) { int count; switch (uriMatcher.match(uri)) { case TASKS: count = todoDB.delete(TODO_TABLE, where, whereArgs); break; case TASK_ID: String segment = uri.getPathSegments().get(1); count = todoDB.delete(TODO_TABLE, KEY_ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { int count; switch (uriMatcher.match(uri)) { case TASKS: count = todoDB.update(TODO_TABLE, values, where, whereArgs); break; case TASK_ID: String segment = uri.getPathSegments().get(1); count = todoDB.update(TODO_TABLE, values, KEY_ID + "=" + segment + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case TASKS: return "vnd.android.cursor.dir/vnd.examples.task"; case TASK_ID: return "vnd.android.cursor.item/vnd.examples.task"; default: throw new IllegalArgumentException("Unsupported URI: " + uri); } } // Create the constants used to differentiate between the different URI // requests. private static final int TASKS = 1; private static final int TASK_ID = 2; private static final UriMatcher uriMatcher; // Allocate the UriMatcher object, where a URI ending in 'tasks' will // correspond to a request for all tasks, and 'tasks' with a // trailing '/[rowID]' will represent a single task row. static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI("com.examples.provider.Todolist", "tasks", TASKS); uriMatcher.addURI("com.examples.provider.Todolist", "tasks/#", TASK_ID); } //The underlying database private SQLiteDatabase todoDB; private static final String TAG = "TodoProvider"; private static final String DATABASE_NAME = "todolist.db"; private static final int DATABASE_VERSION = 1; private static final String TODO_TABLE = "todolist"; // Column Names public static final String KEY_ID = "_id"; public static final String KEY_TASK = "task"; public static final String KEY_CREATION_DATE = "date"; public long insertTask(ToDoItem _task) { // Create a new row of values to insert. ContentValues newTaskValues = new ContentValues(); // Assign values for each row. newTaskValues.put(KEY_TASK, _task.getTask()); newTaskValues.put(KEY_CREATION_DATE, _task.getCreated().getTime()); // Insert the row. return todoDB.insert(TODO_TABLE, null, newTaskValues); } public boolean updateTask(long _rowIndex, String _task) { ContentValues newValue = new ContentValues(); newValue.put(KEY_TASK, _task); return todoDB.update(TODO_TABLE, newValue, KEY_ID + "=" + _rowIndex, null) > 0; } public boolean removeTask(long _rowIndex) { return todoDB.delete(TODO_TABLE, KEY_ID + "=" + _rowIndex, null) > 0; } // Helper class for opening, creating, and managing database version control private static class todoHelper extends SQLiteOpenHelper { private static final String DATABASE_CREATE = "create table " + TODO_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " + KEY_TASK + " TEXT, " + KEY_CREATION_DATE + " INTEGER);"; public todoHelper(Context cn, String name, CursorFactory cf, int ver) { super(cn, name, cf, ver); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + TODO_TABLE); onCreate(db); } } } I've omitted the other files as I'm sure they are correct. When I run the program, LogCat shows that the NullPointerException occurs in populateTodoList(), at toDoListCursor = mService.getAllToDoItemsCursor(). mService is the Cursor object returned by TodoService. I've added the service to the Manifest file, but I still cannot find out why it's causing an exception. Thanks in advance.

    Read the article

  • SwingWorker in Java (beginner question)

    - by Malachi
    I am relatively new to multi-threading and want to execute a background task using a Swingworker thread - the method that is called does not actually return anything but I would like to be notified when it has completed. The code I have so far doesn't appear to be working: private void crawl(ActionEvent evt) { try { SwingWorker<Void, Void> crawler = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { Discoverer discover = new Discoverer(); discover.crawl(); return null; } @Override protected void done() { JOptionPane.showMessageDialog(jfThis, "Finished Crawling", "Success", JOptionPane.INFORMATION_MESSAGE); } }; crawler.execute(); } catch (Exception ex) { JOptionPane.showMessageDialog(this, ex.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE); } } Any feedback/advice would be greatly appreciated as multi-threading is a big area of programming that I am weak in.

    Read the article

  • Adding an overlay to Google maps with path taken

    - by user341652
    Hi, I am trying to write a class to track a person's location(s), and to draw the path they've taken on a MapView. This feature of the program is for the user to track their speed, distance, path, etc. while running/cycling (or whatever else) using their Android phone. This is my first Android application, and I am not sure how to do the Overlay object for the MapView. I also wanted to see if anyone had opinions on the GPS-Tracking part I have written (if it would work, if there is a better way of doing it, code examples would be helpful). I currently have this for my GPSTrackerService: package org.drexel.itrain.logic; import java.util.Vector; import org.drexel.itrain.Constants; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.GpsStatus.Listener; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; public class GPSTrackingService extends Service { private static final int MAX_REASONABLE_SPEED = 60; private static final String TAG = "OGT.TrackingService"; private Context mContext; private LocationManager mLocationManager; private NotificationManager mNotificationManager; private Notification mNotification; private int mSatellites = 0; private int mTrackingState = Constants.GPS_TRACKING_UNKNOWN; private float mCurrentSpeed = 0; private float mTotalDistance = 0; private Location mPreviousLocation; private Vector<Location> mTrackedLocations; private LocationListener mLocationListener = null; private Listener mStatusListener = null; private IBinder binder = null; @Override public void onCreate() { super.onCreate(); this.mContext = getApplicationContext(); this.mLocationManager = (LocationManager) this.mContext.getSystemService( Context.LOCATION_SERVICE ); this.mNotificationManager = (NotificationManager) this.mContext.getSystemService( Context.NOTIFICATION_SERVICE ); this.mTrackedLocations = new Vector<Location>(); this.binder = new Binder(); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.mContext); binder = new Binder(); if(mTrackingState != Constants.GPS_TRACKING_UNKNOWN) { createListeners(); } } @Override public void onDestroy() { destroyListeneres(); } @Override public IBinder onBind(Intent intent) { return binder; } @Override public boolean onUnbind(Intent intent) { return true; } public boolean acceptLocation(Location proposedLocation) { if(!(proposedLocation.hasSpeed() || proposedLocation.hasAccuracy())) { return false; } else if(proposedLocation.getSpeed() >= MAX_REASONABLE_SPEED) { return false; } return true; } public void updateNotification() { //TODO Alert that no GPS sattelites are available (or are available) } public void startTracking() { this.mTrackingState = Constants.GPS_TRACKING_STARTED; this.mTotalDistance = 0; this.mCurrentSpeed = 0; this.mTrackedLocations = new Vector<Location>(); this.mPreviousLocation = null; createListeners(); } public void pauseTracking() { this.mTrackingState = Constants.GPS_TRACKING_PAUSED; this.mPreviousLocation = null; this.mCurrentSpeed = 0; } public void resumeTracking() { if(this.mTrackingState == Constants.GPS_TRACKING_STOPPED){ this.startTracking(); } this.mTrackingState = Constants.GPS_TRACKING_STARTED; } public void stopTracking() { this.mTrackingState = Constants.GPS_TRACKING_STOPPED; destroyListeneres(); } private void createListeners() { /** * LocationListener receives locations from */ this.mLocationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onLocationChanged(Location location) { if(mTrackingState == Constants.GPS_TRACKING_STARTED && acceptLocation(location)) { if(mPreviousLocation != null) { //Add the distance between the new location and the previous location mTotalDistance += mPreviousLocation.distanceTo(location); } if(location.hasSpeed()) { mCurrentSpeed = location.getSpeed(); } else { mCurrentSpeed = -1; //-1 means speed N/A } mPreviousLocation = location; mTrackedLocations.add(location); } } }; /** * Receives updates reguarding the GPS Status */ this.mStatusListener = new GpsStatus.Listener() { @Override public synchronized void onGpsStatusChanged(int event) { switch( event ) { case GpsStatus.GPS_EVENT_SATELLITE_STATUS: { GpsStatus status = mLocationManager.getGpsStatus( null ); mSatellites = 0; Iterable<GpsSatellite> list = status.getSatellites(); for( GpsSatellite satellite : list ) { if( satellite.usedInFix() ) { mSatellites++; } } updateNotification(); break; } default: break; } } }; } /** * Destroys the LocationListenere and the GPSStatusListener */ private void destroyListeneres() { this.mLocationListener = null; this.mStatusListener = null; } /** * Gets the total distance traveled by the * * @return the total distance traveled (in meters) */ public float getDistance() { return mTotalDistance; } /** * Gets the current speed of the last good location * * @return the current speed (in meters/second) */ public float getSpeed() { return mCurrentSpeed; } } Any assistance would be much appreciated. This is my group's first Android app, and we are a little pressed for time at the moment. The project is for a class, and is available from SourceForge (currently called iTrain, soon to be renamed). Thanks in Advance, Steve

    Read the article

  • Implementing callback functions in C

    - by robertjohn123
    Hi, I am a newbie to C.I am trying to implement callback function using function pointers. I am getting an error :test_callback.c:10: error: expected identifier or ‘(’ before ‘void’ when I try to compile the following program: #include<stdio.h> void (*callback) (void); void callback_proc () { printf ("Inside callback funtion\n"); } void register ((void (*callback) (void))) { printf ("Inside registration \n"); callback (); /* Calling an initial callback with function pointer */ } int main () { callback = callback_proc;/* Assigning function to the function pointer */ register (callback);/* Passing the function pointer */ return 0; } What is this error?Can anyone help?

    Read the article

  • Java unit test coverage numbers do not match.

    - by Dan
    Below is a class I have written in a web application I am building using Java Google App Engine. I have written Unit Tests using TestNG and all the tests pass. I then run EclEmma in Eclipse to see the test coverage on my code. All the functions show 100% coverage but the file as a whole is showing about 27% coverage. Where is the 73% uncovered code coming from? Can anyone help me understand how EclEmma works and why I am getting the discrepancy in numbers? package com.skaxo.sports.models; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; @PersistenceCapable(identityType= IdentityType.APPLICATION) public class Account { @PrimaryKey @Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private String userId; @Persistent private String firstName; @Persistent private String lastName; @Persistent private String email; @Persistent private boolean termsOfService; @Persistent private boolean systemEmails; public Account() {} public Account(String firstName, String lastName, String email) { super(); this.firstName = firstName; this.lastName = lastName; this.email = email; } public Account(String userId) { super(); this.userId = userId; } public void setId(Long id) { this.id = id; } public Long getId() { return id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean acceptedTermsOfService() { return termsOfService; } public void setTermsOfService(boolean termsOfService) { this.termsOfService = termsOfService; } public boolean acceptedSystemEmails() { return systemEmails; } public void setSystemEmails(boolean systemEmails) { this.systemEmails = systemEmails; } } Below is the test code for the above class. package com.skaxo.sports.models; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertFalse; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class AccountTest { @Test public void testId() { Account a = new Account(); a.setId(1L); assertEquals((Long) 1L, a.getId(), "ID"); a.setId(3L); assertNotNull(a.getId(), "The ID is set to null."); } @Test public void testUserId() { Account a = new Account(); a.setUserId("123456ABC"); assertEquals(a.getUserId(), "123456ABC", "User ID incorrect."); a = new Account("123456ABC"); assertEquals(a.getUserId(), "123456ABC", "User ID incorrect."); } @Test public void testFirstName() { Account a = new Account("Test", "User", "[email protected]"); assertEquals(a.getFirstName(), "Test", "User first name not equal to 'Test'."); a.setFirstName("John"); assertEquals(a.getFirstName(), "John", "User first name not equal to 'John'."); } @Test public void testLastName() { Account a = new Account("Test", "User", "[email protected]"); assertEquals(a.getLastName(), "User", "User last name not equal to 'User'."); a.setLastName("Doe"); assertEquals(a.getLastName(), "Doe", "User last name not equal to 'Doe'."); } @Test public void testEmail() { Account a = new Account("Test", "User", "[email protected]"); assertEquals(a.getEmail(), "[email protected]", "User email not equal to '[email protected]'."); a.setEmail("[email protected]"); assertEquals(a.getEmail(), "[email protected]", "User email not equal to '[email protected]'."); } @Test public void testAcceptedTermsOfService() { Account a = new Account(); a.setTermsOfService(true); assertTrue(a.acceptedTermsOfService(), "Accepted Terms of Service not true."); a.setTermsOfService(false); assertFalse(a.acceptedTermsOfService(), "Accepted Terms of Service not false."); } @Test public void testAcceptedSystemEmails() { Account a = new Account(); a.setSystemEmails(true); assertTrue(a.acceptedSystemEmails(), "System Emails is not true."); a.setSystemEmails(false); assertFalse(a.acceptedSystemEmails(), "System Emails is not false."); } }

    Read the article

  • Explicit call of Runnable.run

    - by klaudio
    Hi, I have a question. Somebody, who was working on my code before me, created some method and passed Runnable as parameter, more likely: void myMethod(Runnable runnable){ runnable.run(); } Then calling myMethod out of main looks like: public static void main(String args[]) { try { myMethod(new Runnable(){ public void run() { //do something...; }}); } catch (Throwable t) { } } So, to supply parameter to myMethod I need to instantiate object of (in this case anonymous) class implementing Runnable. My question is: is it necessary to use Runnable in this example? Can I use any different interface? I mean I can create new interface with single method i.e. interface MyInterface{ void doThis(); } then change look of myMethod: void myMethod(MyInterface myObject){ myObject.doThis(); } And of course client too: public static void main(String args[]) { try { myMethod(new MyInterface (){ public void doThis() { //do something...; }}); } catch (Throwable t) { } } Or maybe something is about Runnable?!

    Read the article

  • How to test code built to save/restore Lifecycle of an Activity?

    - by Pentium10
    How can I test all of the following methods code? I want to play scenarios when all of them are happening to see if my code works for save/restore process of an activity. So what should I do in the Emulator to get all methods tested? public class Activity extends ApplicationContext { protected void onCreate(Bundle savedInstanceState); protected void onStart(); protected void onRestart(); protected void onResume(); protected void onPause(); protected void onStop(); protected void onDestroy(); }

    Read the article

  • Question about a possible design pattern...

    - by Aftershock
    I have such a design in my mind.... My aim is to reuse the program with some features included and without some features. What is it called in the literature? class feature1 { void feature1function1(); void feature1function2(); } class feature2 { void feature2function1(); void feature2function2(); } class program: feature1, feature2 { void function1() { feature2function1(); } void function2() { feature1function1(); feature2function1(); } void execute() { function1(); function2(); } }

    Read the article

  • How to pass a function to a function?

    - by ShaChris23
    Suppose I have a class with 2 static functions: class CommandHandler { public: static void command_one(Item); static void command_two(Item); }; I have a problem DRY problem where I have 2 functions that have the exact same code for every single line, except for the function that it calls: void CommandOne_User() { // some code A CommandHandler::command_one(item); // some code B } void CommandTwo_User() { // some code A CommandHandler::command_two(item); // some code B } I would like to remove duplication, and, ideally, do something like this: void CommandOne_User() { Function func = CommandHandler::command_one(); Refactored_CommandUser(func); } void CommandTwo_User() { Function func = CommandHandler::command_one(); Refactored_CommandUser(func); } void Refactored_CommandUser(Function func) { // some code A func(item); } I have access to Qt, but not Boost. Could someone help suggest a way on how I can refactor something like this?

    Read the article

  • C++ Reference of vector

    - by void
    Hello, class Refvect { public: vector<int> &refv; Refvect(int t, vector<int> &refv = vector<int>()) : refv(refv) { }; void operator()() { refv.clear(); } }; int main () { Refvect r(0); r(); } With Visual Studio 2010, this gives me an error : "vector iterators incompatible" at the execution, but I don't understand why (but I can insert elements in refv without any problem). The temporary object vector() lives as long as the reference, no?

    Read the article

  • cocos2d-x and handling touch events

    - by Jason
    I have my sprites on screen and I have a vector that stores each sprite. Can a CCSprite* handle a touch event? Or just the CCLayer*? What is the best way to decide what sprite was touched? Should I store the coordinates of where the sprite is (in the sprite class) and when I get the event, see if where the user touched is where the sprite is by looking through the vector and getting each sprites current coordinates? UPDATE: I subclass CCSprite: class Field : public cocos2d::CCSprite, public cocos2d::CCTargetedTouchDelegate and I implement functions: cocos2d::CCRect rect(); virtual void onEnter(); virtual void onExit(); bool containsTouchLocation(cocos2d::CCTouch* touch); virtual bool ccTouchBegan(cocos2d::CCTouch* touch, cocos2d::CCEvent* event); virtual void ccTouchMoved(cocos2d::CCTouch* touch, cocos2d::CCEvent* event); virtual void ccTouchEnded(cocos2d::CCTouch* touch, cocos2d::CCEvent* event); virtual void touchDelegateRetain(); virtual void touchDelegateRelease(); I put CCLOG statements in each one and I dont hit them! When I touch the CCLayer this sprite is on though I do hit those in the class that implements the Layer and puts these sprites on the layer.

    Read the article

  • Cocos2d-x v3 invalid conversion from 'cocos2d::Layer* [on hold]

    - by Hammerh5
    Hello guys I'm learning cocos2d-x v3 right but most of the code that I can find is to the version 2. My specific error is this one, when I try to compile my cocos2s-x 3 project this error shows. invalid conversion from 'cocos2d::Layer to Game* [-fpermisive]* What I want to do is create a new game scene in the following code: //Game.cpp #include "Game.h" Scene* Game::scene() { scene *sc = CCScene::create(); sc->setTag(TAG_GAME_SCENE); const Game *g = Game::create(); //Here is where the conversions fails. sc->addChild(g, 0, TAG_GAME_LAYER); return sc; } Of course this is my header file //Game.h #include "cocos2d.h" #include "Mole.h" #include "AppDelegate.h" using namespace cocos2d; class Game: public cocos2d::Layer { cocos2d::CCArray *moles; float timeBetweenMoles, timeElapsed, increaseMolesAtTime, increaseElapsed, lastMoleHiTime; int molesAtOnce; cocos2d::CCSize s; bool isPaused; public: CCString *missSound, *hitSound; static cocos2d::Scene* scene(); virtual bool init(); void showMole(); void initializeGame(); void onEnterTransitionDidFinish(); void onExit(); void onTouchesBegan(const std::vector<cocos2d::Touch *> &touches, cocos2d::Event *event); void tick(float dt); cocos2d::CCArray* getMoles(bool isUp); //LAYER_CREATE_FUNC(Game); }; #endif /* GAME_H_ */ I don't know what's wrong I suppose this code works fine in Cocos2d-x v2. It's maybe some changes in the C++ version ?

    Read the article

  • Distinguishing repetitive code with the same implementation

    - by KyelJmD
    Given this sample code import java.util.ArrayList; import blackjack.model.items.Card; public class BlackJackPlayer extends Player { private double bet; private Hand hand01 = new Hand(); private Hand hand02 = new Hand(); public void addCardToHand01(Card c) { hand01.addCard(c); } public void addCardToHand02(Card c) { hand02.addCard(c); } public void bustHand01() { hand01.setBust(true); } public void bustHand02() { hand02.setBust(true); } public void standHand01() { hand01.setStand(true); } public void standHand02() { hand02.setStand(true); } public boolean isHand01Bust() { return hand01.isBust(); } public boolean isHand02Bust() { return hand02.isBust(); } public boolean isHand01Standing() { return hand01.isStanding(); } public boolean isHand02Standing() { return hand02.isStanding(); } public int getHand01Score(){ return hand01.getCardScore(); } public int getHand02Score(){ return hand02.getCardScore(); } } Is this considered as a repetitive code? providing that each method is operating a seperate field but doing the same implementation ? Note that hand01 and hand02 should be distinct. if this is considered as repetitive code, how would I address this? providing that each hand is a seperate entity

    Read the article

  • Ogre 3d and bullet physics interaction

    - by Tim
    I have been playing around with Ogre3d and trying to integrate bullet physics. I have previously somewhat successfully got this functionality working with irrlicht and bullet and I am trying to base this on what I had done there, but modifying it to fit with Ogre. It is working but not correctly and I would like some help to understand what it is I am doing wrong. I have a state system and when I enter the "gamestate" I call some functions such as setting up a basic scene, creating the physics simulation. I am doing that as follows. void GameState::enter() { ... // Setup Physics btBroadphaseInterface *BroadPhase = new btAxisSweep3(btVector3(-1000,-1000,-1000), btVector3(1000,1000,1000)); btDefaultCollisionConfiguration *CollisionConfiguration = new btDefaultCollisionConfiguration(); btCollisionDispatcher *Dispatcher = new btCollisionDispatcher(CollisionConfiguration); btSequentialImpulseConstraintSolver *Solver = new btSequentialImpulseConstraintSolver(); World = new btDiscreteDynamicsWorld(Dispatcher, BroadPhase, Solver, CollisionConfiguration); ... createScene(); } In the createScene method I add a light and try to setup a "ground" plane to act as the ground for things to collide with.. as follows. I expect there is issues with this as I get objects colliding with the ground but half way through it and they glitch around like crazy on collision. void GameState::createScene() { m_pSceneMgr->createLight("Light")->setPosition(75,75,75); // Physics // As a test we want a floor plane for things to collide with Ogre::Entity *ent; Ogre::Plane p; p.normal = Ogre::Vector3(0,1,0); p.d = 0; Ogre::MeshManager::getSingleton().createPlane( "FloorPlane", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, p, 200000, 200000, 20, 20, true, 1, 9000,9000,Ogre::Vector3::UNIT_Z); ent = m_pSceneMgr->createEntity("floor", "FloorPlane"); ent->setMaterialName("Test/Floor"); Ogre::SceneNode *node = m_pSceneMgr->getRootSceneNode()->createChildSceneNode(); node->attachObject(ent); btTransform Transform; Transform.setIdentity(); Transform.setOrigin(btVector3(0,1,0)); // Give it to the motion state btDefaultMotionState *MotionState = new btDefaultMotionState(Transform); btCollisionShape *Shape = new btStaticPlaneShape(btVector3(0,1,0),0); // Add Mass btVector3 LocalInertia; Shape->calculateLocalInertia(0, LocalInertia); // CReate the rigid body object btRigidBody *RigidBody = new btRigidBody(0, MotionState, Shape, LocalInertia); // Store a pointer to the Ogre Node so we can update it later RigidBody->setUserPointer((void *) (node)); // Add it to the physics world World->addRigidBody(RigidBody); Objects.push_back(RigidBody); m_pNumEntities++; // End Physics } I then have a method to create a cube and give it rigid body physics properties. I know there will be errors here as I get the items colliding with the ground but not with each other properly. So I would appreciate some input on what I am doing wrong. void GameState::CreateBox(const btVector3 &TPosition, const btVector3 &TScale, btScalar TMass) { Ogre::Vector3 size = Ogre::Vector3::ZERO; Ogre::Vector3 pos = Ogre::Vector3::ZERO; Ogre::Vector3 scale = Ogre::Vector3::ZERO; pos.x = TPosition.getX(); pos.y = TPosition.getY(); pos.z = TPosition.getZ(); scale.x = TScale.getX(); scale.y = TScale.getY(); scale.z = TScale.getZ(); Ogre::Entity *entity = m_pSceneMgr->createEntity( "Box" + Ogre::StringConverter::toString(m_pNumEntities), "cube.mesh"); entity->setCastShadows(true); Ogre::AxisAlignedBox boundingB = entity->getBoundingBox(); size = boundingB.getSize(); //size /= 2.0f; // Only the half needed? //size *= 0.96f; // Bullet margin is a bit bigger so we need a smaller size entity->setMaterialName("Test/Cube"); Ogre::SceneNode *node = m_pSceneMgr->getRootSceneNode()->createChildSceneNode(); node->attachObject(entity); node->setPosition(pos); //node->scale(scale); // Physics btTransform Transform; Transform.setIdentity(); Transform.setOrigin(TPosition); // Give it to the motion state btDefaultMotionState *MotionState = new btDefaultMotionState(Transform); btVector3 HalfExtents(TScale.getX()*0.5f,TScale.getY()*0.5f,TScale.getZ()*0.5f); btCollisionShape *Shape = new btBoxShape(HalfExtents); // Add Mass btVector3 LocalInertia; Shape->calculateLocalInertia(TMass, LocalInertia); // CReate the rigid body object btRigidBody *RigidBody = new btRigidBody(TMass, MotionState, Shape, LocalInertia); // Store a pointer to the Ogre Node so we can update it later RigidBody->setUserPointer((void *) (node)); // Add it to the physics world World->addRigidBody(RigidBody); Objects.push_back(RigidBody); m_pNumEntities++; } Then in the GameState::update() method which which runs every frame to handle input and render etc I call an UpdatePhysics method to update the physics simulation. void GameState::UpdatePhysics(unsigned int TDeltaTime) { World->stepSimulation(TDeltaTime * 0.001f, 60); btRigidBody *TObject; for(std::vector<btRigidBody *>::iterator it = Objects.begin(); it != Objects.end(); ++it) { // Update renderer Ogre::SceneNode *node = static_cast<Ogre::SceneNode *>((*it)->getUserPointer()); TObject = *it; // Set position btVector3 Point = TObject->getCenterOfMassPosition(); node->setPosition(Ogre::Vector3((float)Point[0], (float)Point[1], (float)Point[2])); // set rotation btVector3 EulerRotation; QuaternionToEuler(TObject->getOrientation(), EulerRotation); node->setOrientation(1,(Ogre::Real)EulerRotation[0], (Ogre::Real)EulerRotation[1], (Ogre::Real)EulerRotation[2]); //node->rotate(Ogre::Vector3(EulerRotation[0], EulerRotation[1], EulerRotation[2])); } } void GameState::QuaternionToEuler(const btQuaternion &TQuat, btVector3 &TEuler) { btScalar W = TQuat.getW(); btScalar X = TQuat.getX(); btScalar Y = TQuat.getY(); btScalar Z = TQuat.getZ(); float WSquared = W * W; float XSquared = X * X; float YSquared = Y * Y; float ZSquared = Z * Z; TEuler.setX(atan2f(2.0f * (Y * Z + X * W), -XSquared - YSquared + ZSquared + WSquared)); TEuler.setY(asinf(-2.0f * (X * Z - Y * W))); TEuler.setZ(atan2f(2.0f * (X * Y + Z * W), XSquared - YSquared - ZSquared + WSquared)); TEuler *= RADTODEG; } I seem to have issues with the cubes not colliding with each other and colliding strangely with the ground. I have tried to capture the effect with the attached image. I would appreciate any help in understanding what I have done wrong. Thanks. EDIT : Solution The following code shows the changes I made to get accurate physics. void GameState::createScene() { m_pSceneMgr->createLight("Light")->setPosition(75,75,75); // Physics // As a test we want a floor plane for things to collide with Ogre::Entity *ent; Ogre::Plane p; p.normal = Ogre::Vector3(0,1,0); p.d = 0; Ogre::MeshManager::getSingleton().createPlane( "FloorPlane", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, p, 200000, 200000, 20, 20, true, 1, 9000,9000,Ogre::Vector3::UNIT_Z); ent = m_pSceneMgr->createEntity("floor", "FloorPlane"); ent->setMaterialName("Test/Floor"); Ogre::SceneNode *node = m_pSceneMgr->getRootSceneNode()->createChildSceneNode(); node->attachObject(ent); btTransform Transform; Transform.setIdentity(); // Fixed the transform vector here for y back to 0 to stop the objects sinking into the ground. Transform.setOrigin(btVector3(0,0,0)); // Give it to the motion state btDefaultMotionState *MotionState = new btDefaultMotionState(Transform); btCollisionShape *Shape = new btStaticPlaneShape(btVector3(0,1,0),0); // Add Mass btVector3 LocalInertia; Shape->calculateLocalInertia(0, LocalInertia); // CReate the rigid body object btRigidBody *RigidBody = new btRigidBody(0, MotionState, Shape, LocalInertia); // Store a pointer to the Ogre Node so we can update it later RigidBody->setUserPointer((void *) (node)); // Add it to the physics world World->addRigidBody(RigidBody); Objects.push_back(RigidBody); m_pNumEntities++; // End Physics } void GameState::CreateBox(const btVector3 &TPosition, const btVector3 &TScale, btScalar TMass) { Ogre::Vector3 size = Ogre::Vector3::ZERO; Ogre::Vector3 pos = Ogre::Vector3::ZERO; Ogre::Vector3 scale = Ogre::Vector3::ZERO; pos.x = TPosition.getX(); pos.y = TPosition.getY(); pos.z = TPosition.getZ(); scale.x = TScale.getX(); scale.y = TScale.getY(); scale.z = TScale.getZ(); Ogre::Entity *entity = m_pSceneMgr->createEntity( "Box" + Ogre::StringConverter::toString(m_pNumEntities), "cube.mesh"); entity->setCastShadows(true); Ogre::AxisAlignedBox boundingB = entity->getBoundingBox(); // The ogre bounding box is slightly bigger so I am reducing it for // use with the rigid body. size = boundingB.getSize()*0.95f; entity->setMaterialName("Test/Cube"); Ogre::SceneNode *node = m_pSceneMgr->getRootSceneNode()->createChildSceneNode(); node->attachObject(entity); node->setPosition(pos); node->showBoundingBox(true); //node->scale(scale); // Physics btTransform Transform; Transform.setIdentity(); Transform.setOrigin(TPosition); // Give it to the motion state btDefaultMotionState *MotionState = new btDefaultMotionState(Transform); // I got the size of the bounding box above but wasn't using it to set // the size for the rigid body. This now does. btVector3 HalfExtents(size.x*0.5f,size.y*0.5f,size.z*0.5f); btCollisionShape *Shape = new btBoxShape(HalfExtents); // Add Mass btVector3 LocalInertia; Shape->calculateLocalInertia(TMass, LocalInertia); // CReate the rigid body object btRigidBody *RigidBody = new btRigidBody(TMass, MotionState, Shape, LocalInertia); // Store a pointer to the Ogre Node so we can update it later RigidBody->setUserPointer((void *) (node)); // Add it to the physics world World->addRigidBody(RigidBody); Objects.push_back(RigidBody); m_pNumEntities++; } void GameState::UpdatePhysics(unsigned int TDeltaTime) { World->stepSimulation(TDeltaTime * 0.001f, 60); btRigidBody *TObject; for(std::vector<btRigidBody *>::iterator it = Objects.begin(); it != Objects.end(); ++it) { // Update renderer Ogre::SceneNode *node = static_cast<Ogre::SceneNode *>((*it)->getUserPointer()); TObject = *it; // Set position btVector3 Point = TObject->getCenterOfMassPosition(); node->setPosition(Ogre::Vector3((float)Point[0], (float)Point[1], (float)Point[2])); // Convert the bullet Quaternion to an Ogre quaternion btQuaternion btq = TObject->getOrientation(); Ogre::Quaternion quart = Ogre::Quaternion(btq.w(),btq.x(),btq.y(),btq.z()); // use the quaternion with setOrientation node->setOrientation(quart); } } The QuaternionToEuler function isn't needed so that was removed from code and header files. The objects now collide with the ground and each other appropriately.

    Read the article

  • VBO and shaders confusion, what's their connection?

    - by Jeffrey
    Considering OpenGL 2.1 VBOs and 1.20 GLSL shaders: When creating an entity like "Zombie", is it good to initialize just the VBO buffer with the data once and do N glDrawArrays() calls per each N zombies? Is there a more efficient way? (With a single call we cannot pass different uniforms to the shader to calculate an offset, see point 3) When dealing with logical object (player, tree, cube etc), should I always use the same shader or should I customize (or be able to customize) the shaders per each object? Considering an entity class, should I create and define the shader at object initialization? When having a movable object such as a human, is there any more powerful way to deal with its coordinates than to initialize its VBO object at 0,0 and define an uniform offset to pass to the shader to calculate its real position? Could you make an example of the Data Oriented Design on creating a generic zombie class? Is the following good? Zombielist class: class ZombieList { GLuint vbo; // generic zombie vertex model std::vector<color>; // object default color std::vector<texture>; // objects textures std::vector<vector3D>; // objects positions public: unsigned int create(); // return object id void move(unsigned int objId, vector3D offset); void rotate(unsigned int objId, float angle); void setColor(unsigned int objId, color c); void setPosition(unsigned int objId, color c); void setTexture(unsigned int, unsigned int); ... void update(Player*); // move towards player, attack if near } Example: Player p; Zombielist zl; unsigned int first = zl.create(); zl.setPosition(first, vector3D(50, 50)); zl.setTexture(first, texture("zombie1.png")); ... while (running) { // main loop ... zl.update(&p); zl.draw(); // draw every zombie }

    Read the article

  • How to implement a stack of game states in C++

    - by Lisandro Vaccaro
    I'm new to C++ and as a college proyect I'm building a 2D platformer with some classmates, I recently read that it's a good idea to have a stack of gamestates instead of a single global variable with the game state (which is what I have now) but I'm not sure how to do it. Currently this is my implementation: class GameState { public: virtual ~GameState(){}; virtual void handle_events() = 0; virtual void logic() = 0; virtual void render() = 0; }; class Menu : public GameState { public: Menu(); ~Menu(); void handle_events(); void logic(); void render(); }; Then I have a global variable of type GameState: GameState *currentState = NULL; And in my Main I define the currentState and call it's methods: int main(){ currentState = new Menu(); currentState.handle_events(); } How can I implement a stack or something similar to go from that to something like this: int main(){ statesStack.push(new Menu()); statesStack.getTop().handle_events(); }

    Read the article

  • First Person Camera strafing at angle

    - by Linkandzelda
    I have a simple camera class working in directx 11 allowing moving forward and rotating left and right. I'm trying to implement strafing into it but having some problems. The strafing works when there's no camera rotation, so when the camera starts at 0, 0, 0. But after rotating the camera in either direction it seems to strafe at an angle or inverted or just some odd stuff. Here is a video uploaded to Dropbox showing this behavior. https://dl.dropboxusercontent.com/u/2873587/IncorrectStrafing.mp4 And here is my camera class. I have a hunch that it's related to the calculation for camera position. I tried various different calculations in strafe and they all seem to follow the same pattern and same behavior. Also the m_camera_rotation represents the Y rotation, as pitching isn't implemented yet. #include "camera.h" camera::camera(float x, float y, float z, float initial_rotation) { m_x = x; m_y = y; m_z = z; m_camera_rotation = initial_rotation; updateDXZ(); } camera::~camera(void) { } void camera::updateDXZ() { m_dx = sin(m_camera_rotation * (XM_PI/180.0)); m_dz = cos(m_camera_rotation * (XM_PI/180.0)); } void camera::Rotate(float amount) { m_camera_rotation += amount; updateDXZ(); } void camera::Forward(float step) { m_x += step * m_dx; m_z += step * m_dz; } void camera::strafe(float amount) { float yaw = (XM_PI/180.0) * m_camera_rotation; m_x += cosf( yaw ) * amount; m_z += sinf( yaw ) * amount; } XMMATRIX camera::getViewMatrix() { updatePosition(); return XMMatrixLookAtLH(m_position, m_lookat, m_up); } void camera::updatePosition() { m_position = XMVectorSet(m_x, m_y, m_z, 0.0); m_lookat = XMVectorSet(m_x + m_dx, m_y, m_z + m_dz, 0.0); m_up = XMVectorSet(0.0, 1.0, 0.0, 0.0); }

    Read the article

  • Libgdx actor bounds are wrong

    - by Undume
    The Actor's boundaries are not centered at the ButtonText but I used the setBounds() method. The higher the Y position is, the less centered is the boundary. The weird thing is that i only created and added to the Stage one button but the screen shows two. When i click the top button, the bottom one is the one highlighted. How can i fix that? import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; public class MyGame extends Game { Stage stage; @Override public void create() { stage=new Stage(); FileHandle skinFile = new FileHandle("data/resources/uiskin/uiskin.json"); Skin skin = new Skin(skinFile); TextButton sas=new TextButton("dd",skin); sas.setBounds(0, 500, 100, 100); stage.addActor(sas); Gdx.input.setInputProcessor(stage); } @Override public void dispose() { super.dispose(); } @Override public void render() { super.render(); stage.act(Gdx.graphics.getDeltaTime()); stage.draw(); } @Override public void resize(int width, int height) { super.resize(width, height); } @Override public void pause() { super.pause(); } @Override public void resume() { super.resume(); } }

    Read the article

< Previous Page | 14 15 16 17 18 19 20 21 22 23 24 25  | Next Page >