Search Results

Search found 180 results on 8 pages for 'eugene lim'.

Page 6/8 | < Previous Page | 2 3 4 5 6 7 8  | Next Page >

  • Unexpected ArrayIndexOutOfBoundsException in JavaFX application, refering to no array

    - by Eugene
    I have the following code: public void setContent(Importer3D importer) { if (DEBUG) { System.out.println("Initialization of Mesh's arrays"); } coords = importer.getCoords(); texCoords = importer.getTexCoords(); faces = importer.getFaces(); if (DEBUG) { System.out.println("Applying Mesh's arrays"); } mesh = new TriangleMesh(); mesh.getPoints().setAll(coords); mesh.getTexCoords().setAll(texCoords); mesh.getFaces().setAll(faces); if (DEBUG) { System.out.println("Initialization of the material"); } initMaterial(); if (DEBUG) { System.out.println("Setting the MeshView"); } meshView.setMesh(mesh); meshView.setMaterial(material); meshView.setDrawMode(DrawMode.FILL); if (DEBUG) { System.out.println("Adding to 3D scene"); } root3d.getChildren().clear(); root3d.getChildren().add(meshView); if (DEBUG) { System.out.println("3D model is ready!"); } } The Imporeter3D class part: private void load(File file) { stlLoader = new STLLoader(file); } public float[] getCoords() { return stlLoader.getCoords(); } public float[] getTexCoords() { return stlLoader.getTexCoords(); } public int[] getFaces() { return stlLoader.getFaces(); } The STLLoader: public class STLLoader{ public STLLoader(File file) { stlFile = new STLFile(file); loadManager = stlFile.loadManager; pointsArray = new PointsArray(stlFile); texCoordsArray = new TexCoordsArray(); } public float[] getCoords() { return pointsArray.getPoints(); } public float[] getTexCoords() { return texCoordsArray.getTexCoords(); } public int[] getFaces() { return pointsArray.getFaces(); } private STLFile stlFile; private PointsArray pointsArray; private TexCoordsArray texCoordsArray; private FacesArray facesArray; public SimpleBooleanProperty finished = new SimpleBooleanProperty(false); public LoadManager loadManager;} PointsArray file: public class PointsArray { public PointsArray(STLFile stlFile) { this.stlFile = stlFile; initPoints(); } private void initPoints() { ArrayList<Double> pointsList = stlFile.getPoints(); ArrayList<Double> uPointsList = new ArrayList<>(); faces = new int[pointsList.size()*2]; int n = 0; for (Double d : pointsList) { if (uPointsList.indexOf(d) == -1) { uPointsList.add(d); } faces[n] = uPointsList.indexOf(d); faces[++n] = 0; n++; } int i = 0; points = new float[uPointsList.size()]; for (Double d : uPointsList) { points[i] = d.floatValue(); i++; } } public float[] getPoints() { return points; } public int[] getFaces() { return faces; } private float[] points; private int[] faces; private STLFile stlFile; public static boolean DEBUG = true; } And STLFile: ArrayList<Double> coords = new ArrayList<>(); double temp; private void readV(STLParser parser) { for (int n = 0; n < 3; n++) { if(!(parser.ttype==STLParser.TT_WORD && parser.sval.equals("vertex"))) { System.err.println("Format Error:expecting 'vertex' on line " + parser.lineno()); } else { if (parser.getNumber()) { temp = parser.nval; coords.add(temp); if(DEBUG) { System.out.println("Vertex:"); System.out.print("X=" + temp + " "); } if (parser.getNumber()) { temp = parser.nval; coords.add(temp); if(DEBUG) { System.out.print("Y=" + temp + " "); } if (parser.getNumber()) { temp = parser.nval; coords.add(temp); if(DEBUG) { System.out.println("Z=" + temp + " "); } readEOL(parser); } else System.err.println("Format Error: expecting coordinate on line " + parser.lineno()); } else System.err.println("Format Error: expecting coordinate on line " + parser.lineno()); } else System.err.println("Format Error: expecting coordinate on line " + parser.lineno()); } if (n < 2) { try { parser.nextToken(); } catch (IOException e) { System.err.println("IO Error on line " + parser.lineno() + ": " + e.getMessage()); } } } } public ArrayList<Double> getPoints() { return coords; } As a result of all of this code, I expected to get 3d model in MeshView. But the present result is very strange: everything works and in DEBUG mode I get 3d model is ready! from setContent(), and then unexpected ArrayIndexOutOfBoundsException: File readed Initialization of Mesh's arrays Applying Mesh's arrays Initialization of the material Setting the MeshView Adding to 3D scene 3D model is ready! java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 32252 at com.sun.javafx.collections.ObservableFloatArrayImpl.rangeCheck(ObservableFloatArrayImpl.java:276) at com.sun.javafx.collections.ObservableFloatArrayImpl.get(ObservableFloatArrayImpl.java:184) at javafx.scene.shape.TriangleMesh.computeBounds(TriangleMesh.java:262) at javafx.scene.shape.MeshView.impl_computeGeomBounds(MeshView.java:151) at javafx.scene.Node.updateGeomBounds(Node.java:3497) at javafx.scene.Node.getGeomBounds(Node.java:3450) at javafx.scene.Node.getLocalBounds(Node.java:3432) at javafx.scene.Node.updateTxBounds(Node.java:3510) at javafx.scene.Node.getTransformedBounds(Node.java:3350) at javafx.scene.Node.updateBounds(Node.java:516) at javafx.scene.Parent.updateBounds(Parent.java:1668) at javafx.scene.SubScene.updateBounds(SubScene.java:556) at javafx.scene.Parent.updateBounds(Parent.java:1668) at javafx.scene.Parent.updateBounds(Parent.java:1668) at javafx.scene.Parent.updateBounds(Parent.java:1668) at javafx.scene.Parent.updateBounds(Parent.java:1668) at javafx.scene.Parent.updateBounds(Parent.java:1668) at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2309) at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:329) at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:479) at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:459) at com.sun.javafx.tk.quantum.QuantumToolkit$13.run(QuantumToolkit.java:326) at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95) at com.sun.glass.ui.win.WinApplication._runLoop(Native Method) at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39) at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:101) at java.lang.Thread.run(Thread.java:724) Exception in thread "JavaFX Application Thread" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 32252 at com.sun.javafx.collections.ObservableFloatArrayImpl.rangeCheck(ObservableFloatArrayImpl.java:276) at com.sun.javafx.collections.ObservableFloatArrayImpl.get(ObservableFloatArrayImpl.java:184) The stranger thing is that this stack doesn't stop until I close the program. And moreover it doesn't point to any my array. What is this? And why does it happen?

    Read the article

  • (illustrator scripting) how to release objects to layers(sequence) but retain object's name?

    - by Eugene
    Hi, I've asked the same question to adobe scripting forum. but seems there are not many forum users there, and I'm asking the same question here. I was writing my first illustrator script to export all layers to png files with layer structure converted to file structure. I found there are many layers that my script can't detect and found out that they are not actually layers but objects(or groups). Found a layer menu (release to layers), but doesn't quite solve the problem perfectly. initially I have this layer 001 object 01 object 1 object 2 release to layers(sequence) on object 01 gives layer 001 layer 91(whatever the layer number illustrator gives when release to layers are performed) layer 92 object 1 layer 93 object 2 now I need to convert them to (so that layer can retain the name of the object) layer 001 layer 01 layer 1 object 1 layer 2 object 2 I have hundreds of layer 001, and couple thousands of object 01, and wonder if anything can be done with script to do this... If it's possible to detect object in a script, I could rewrite the 'release to layers' functionality in script maybe. Any help would be greatly appreciated.

    Read the article

  • NullReferenceException at Microsoft.Silverlight.Build.Tasks.CompileXaml.LoadAssemblies(ITaskItem[] R

    - by Eugene Larchick
    Hi, I updated my Visual Studio 2010 to the version 10.0.30319.1 RTM Rel and start getting the following exception during the build: System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.Silverlight.Build.Tasks.CompileXaml.LoadAssemblies(ITaskItem[] ReferenceAssemblies) at Microsoft.Silverlight.Build.Tasks.CompileXaml.get_GetXamlSchemaContext() at Microsoft.Silverlight.Build.Tasks.CompileXaml.GenerateCode(ITaskItem item, Boolean isApplication) at Microsoft.Silverlight.Build.Tasks.CompileXaml.Execute() at Bohr.Silverlight.BuildTasks.BohrCompileXaml.Execute() The code of BohrCompileXaml.Execute is the following: public override bool Execute() { List<TaskItem> pages = new List<TaskItem>(); foreach (ITaskItem item in SilverlightPages) { string newFileName = getGeneratedName(item.ItemSpec); String content = File.ReadAllText(item.ItemSpec); String parentClassName = getParentClassName(content); if (null != parentClassName) { content = content.Replace("<UserControl", "<" + parentClassName); content = content.Replace("</UserControl>", "</" + parentClassName + ">"); content = content.Replace("bohr:ParentClass=\"" + parentClassName + "\"", ""); } File.WriteAllText(newFileName, content); pages.Add(new TaskItem(newFileName)); } if (null != SilverlightApplications) { foreach (ITaskItem item in SilverlightApplications) { Log.LogMessage(MessageImportance.High, "Application: " + item.ToString()); } } foreach (ITaskItem item in pages) { Log.LogMessage(MessageImportance.High, "newPage: " + item.ToString()); } CompileXaml xamlCompiler = new CompileXaml(); xamlCompiler.AssemblyName = AssemblyName; xamlCompiler.Language = Language; xamlCompiler.LanguageSourceExtension = LanguageSourceExtension; xamlCompiler.OutputPath = OutputPath; xamlCompiler.ProjectPath = ProjectPath; xamlCompiler.RootNamespace = RootNamespace; xamlCompiler.SilverlightApplications = SilverlightApplications; xamlCompiler.SilverlightPages = pages.ToArray(); xamlCompiler.TargetFrameworkDirectory = TargetFrameworkDirectory; xamlCompiler.TargetFrameworkSDKDirectory = TargetFrameworkSDKDirectory; xamlCompiler.BuildEngine = BuildEngine; bool result = xamlCompiler.Execute(); // HERE we got the error! And the definition of the task: <BohrCompileXaml LanguageSourceExtension="$(DefaultLanguageSourceExtension)" Language="$(Language)" SilverlightPages="@(Page)" SilverlightApplications="@(ApplicationDefinition)" ProjectPath="$(MSBuildProjectFullPath)" RootNamespace="$(RootNamespace)" AssemblyName="$(AssemblyName)" OutputPath="$(IntermediateOutputPath)" TargetFrameworkDirectory="$(TargetFrameworkDirectory)" TargetFrameworkSDKDirectory="$(TargetFrameworkSDKDirectory)" > <Output ItemName="Compile" TaskParameter="GeneratedCodeFiles" /> <!-- Add to the list list of files written. It is used in Microsoft.Common.Targets to clean up for a next clean build --> <Output ItemName="FileWrites" TaskParameter="WrittenFiles" /> <Output ItemName="_GeneratedCodeFiles" TaskParameter="GeneratedCodeFiles" /> </BohrCompileXaml> What can be the reason? And how can I get more info what's happening inside CompileXaml class?

    Read the article

  • Apache/2.2.9, mod_perl/2.0.4: status_line doesn't seem to work

    - by Eugene
    Response is prepared this way: my $r = Apache2::RequestUtil->request; $r->status_line('500 Internal Server Error'); $r->send_cgi_header("Content-Type: text/html; charset=UTF-8\n\n"); print 'Custom error message'; Request: GET /test_page HTTP/1.1 Host: www.xxx.xxx Response: HTTP/1.1 200 OK Date: XXXXXXXXXX Server: Apache/xxxxxxxx Vary: Accept-Encoding Transfer-Encoding: chunked Content-Type: text/html; charset=UTF-8 44 Custom error message 0 Why response status is 200 and not 500?

    Read the article

  • Who owns forum users or are user grabbers legal?

    - by Eugene
    Hi, I am not very strong in "legal or not" questions so I hope someone can help me here. How legal is the following: I create my forum, then choose a random existing forum (not mine), take a user from that forum (username, avatar, etc) and create an identical account at my forum. I know that this is extremely hard to prove and everything but anyway: how legal are the described actions? Thanks!

    Read the article

  • django-haystack urlpatterns include('haystack.urls') where does it lead to?

    - by Eugene
    I've recently begun to learn/install django/haystack/solr. Following the tutorial given in haystack site, I have urlpatterns = pattern('', r'^search/', include('haystack.urls')) I found haystack installed in /usr/local/lib/python2.6/dist-packages/haystack and located urls.py there. It has urlpatterns=patterns('haystack.views', url(r'^$', SearchView(), name='haystack_search'),) I thought the second argument of url() should be callable object. I looked at the views.py and SearchView is a class. What is going on here? What's get called eventually?

    Read the article

  • How to pass a touch event to other views?

    - by Eugene
    +-----------------------+ +--------------------+ | A | | A | | +-------------------+ | | +----------------+ | | |B | | | | C | | | | | | | | | | | +-------------------+ | | +----------------+ | +-----------------------+ +--------------------+ I have a view hierarchy as above. (Each of B and C takes up whole space of A, Each of them are screen size. B is added first and C is added next) For a reason, C is getting a touch event for scroll effect (B is cocos2d-x layer and C(scroll view) sets the B's position when scrollViewDidScroll http://getsetgames.com/2009/08/21/cocos2d-and-uiscrollview/ ) And I want to pass touch event to B or it's subviews when it's not scrolling. How can I pass the touch event to B here?

    Read the article

  • Accepted date format changed overnight

    - by Eugene Niemand
    Since yesterday I started encountering errors related to date formats in SQL Server 2008. Up until yesterday the following used to work. EXEC MyStoredProc '2010-03-15 00:00:00.000' Since yesterday I started getting out of range errors. After investigating I discovered the date as above is now being interpreted as "the 3rd of the 15th month" which will cause a out of range error. I have been able to fix this using the following format with the "T". EXEC MyStoredProc '2010-03-15T00:00:00.000' By using this format its working fine. Basically all I'm trying to find out is if there is some Hotfix or patch that could have caused this, as all my queries using the first mentioned formats have been working for months. Also this is not a setting that was changed by someone in the company as this is occurring on all SQL 2005/2008 servers

    Read the article

  • android.permission.CALL_PHONE: making single apk for phones and tablets:

    - by Eugene Chumak
    I want my app to be available for both phones and tablets. The only difference between phone and tablet versions is: in "phone" version my app has buttons, which allow to make a phone call to a certain number. What is my problem: to be able to make phone call I need to add a permission to manifest file - <uses-permission android:name="android.permission.CALL_PHONE" /> This permission makes application incompatible with tablets. If I remove the permission, app cant make calls being launched on phone. How to make an app, that supports both phones and tablets and allow to make calls from phones?

    Read the article

  • Python. Strange class attributes behavior

    - by Eugene
    >>> class Abcd: ... a = '' ... menu = ['a', 'b', 'c'] ... >>> a = Abcd() >>> b = Abcd() >>> a.a = 'a' >>> b.a = 'b' >>> a.a 'a' >>> b.a 'b' It's all correct and each object has own 'a', but... >>> a.menu.pop() 'c' >>> a.menu ['a', 'b'] >>> b.menu ['a', 'b'] How could this happen? And how to use list as class attribute?

    Read the article

  • Setting custom SQL in django admin

    - by eugene y
    I'm trying to set up a proxy model in django admin. It will represent a subset of the original model. The code from models.py: class MyManager(models.Manager): def get_query_set(self): return super(MyManager, self).get_query_set().filter(some_column='value') class MyModel(OrigModel): objects = MyManager() class Meta: proxy = True Now instead of filter() I need to use a complex SELECT statement with JOINS. What's the proper way to inject it wholly to the custom manager?

    Read the article

  • (iphone) maintaining CGContextRef or CGLayerRef is a bad idea?

    - by Eugene
    Hi, I need to work with many images, and I can't hold them as UIImage in memory because they are too big. I also need to change colors of image and merge them on the fly. Creating UIImage from underlying NSData, change color, and combine them when you can't have many images on memory is fairly slow. (as far as I can get) I thought maybe I can store underlying CGLayerRef(for image that will be combined) and CGContextRef(the resulting combined image). I am new to drawing world, and not sure if CGLayerRef or CGContextRef is smaller in memory than UIImage. I recently heard that w*h image takes up w*h*4 bytes in memory. Does CGLayerRef or CGContextRef also take up that much memory? Thank you

    Read the article

  • (iphone) can i give different intervals between images when animating?

    - by Eugene
    Hi, I'm animating several image as follows. UIImageView* animationView = [[UIImageView alloc] initWithFrame: self.animationViewContainer.bounds]; animationView.animationImages = animationArray; animationView.animationDuration = 0.5; animationView.animationRepeatCount = 5; [animationView startAnimating]; What I'd like to do is, controlling duration between animationImages. For instance, show image1 for 0.3 sec image2 for 0.5 sec.. There must be some way to do this, but hard to find an answer. I've asked the same question here before, but wording of the question wasn't so clear. Thank you

    Read the article

  • Selecting from a Large Table SQL 2005

    - by Eugene
    I have a SQL table it has more than 1000000 rows, and I need to select with the query as you can see below: SELECT DISTINCT TOP (200) COUNT(1) AS COUNT, KEYWORD FROM QUERIES WITH(NOLOCK) WHERE KEYWORD LIKE '%Something%' GROUP BY KEYWORD ORDER BY 'COUNT' DESC Could you please tell me how can I optimize it to speed up the execution process? Thank you for useful answers.

    Read the article

  • How to correctly configure server for Symfony (on shared hosting)?

    - by Eugene
    Hi! I've decided to learn Symfony and right now I am reading through the very start of the "Practical Symfony" book. After reading the "Web Server Configuration" part I have a question. The manual is describing how to correctly configure the server: browser should have access only to web/ and sf/.../ directories. The manual has great instructions regarding this and being a Linux user I had no problem following them and making everything work on my local machine. However that involves editing VirtualHost entries which normally is not easy to do on common shared hosting servers. So I wonder what is the common technique that Symfony developers use to get the same results in shared hosting environment? I think I can do that by adding "deny from all" in the root and then overwriting that rule in the allowed directories. However I am not sure if that's the easiest way and the way that is normally used.

    Read the article

  • Get info about Http Post field order

    - by Eugene
    Is it possible to get information about post field order in ASP.NET? I need to know whether some field was the last one or not. I know I can do it through Request.InputStream, but I’m looking for a more high level solution without manually stream parsing. Generally I’m doing testing of http post sent by my application and there is no practical usage for this in ASP.NET.

    Read the article

  • (iphone) am I creating a leak when creating a new image from an image?

    - by Eugene
    Hi, I have following code as UIImage+Scale.h category. -(UIImage*)scaleToSize:(CGSize)size { UIGraphicsBeginImageContext(size); [self drawInRect:CGRectMake(0, 0, size.width, size.height)]; // is this scaledImage auto-released? UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; } I use image obtained as above and use it as following. UIImage* image = [[UIImage alloc] initWithData: myData]; image = [image scaleToSize: size]; <- wouldn't this code create a leak since image(before scaling) is lost somewhere? i guess above codes work fine if image was first created with auto-release. But if image was created using 'alloc', it would create a leak in my short knowledge. How should I change scaleToSize: to guard against it? Thank you

    Read the article

  • How can I map URLs to filenames with perl?

    - by eugene y
    In a simple webapp I need to map URLs to filenames or filepaths. This app has a requirement that it can depend only on modules in the core Perl ditribution (5.6.0 and later). The problem is that filename length on most filesystems is limited to 255. Another limit is about 32k subdirectories in a single folder. My solution: my $filename = $url; if (length($filename) > $MAXPATHLEN) { # if filename longer than 255 my $part1 = substr($filename, 0, $MAXPATHLEN - 13); # first 242 chars my $part2 = crypt(0, substr($filename, $MAXPATHLEN - 13)); # 13 chars hash $filename = $part1.$part2; } $filename =~ s!/!_!g; # escape directory separator Is it reliable ? How can it be improved ?

    Read the article

  • GTK+: How do I process RadioMenuItem choice without marking it chosen? And vise versa

    - by eugene.shatsky
    In my program, I've got a menu with a group of RadioMenuItem entries. Choosing one of them should trigger a function which can either succeed or fail. If it fails, this RadioMenuItem shouldn't be marked chosen (the previous one should persist). Besides, sometimes I want to set marked item without running the choice processing function. Here is my current code: # Update seat menu list def update_seat_menu(self, seats, selected_seat=None): seat_menu = self.builder.get_object('seat_menu') # Delete seat menu items for menu_item in seat_menu: # TODO: is it a good way? does remove() delete obsolete menu_item from memory? if menu_item.__class__.__name__ == 'RadioMenuItem': seat_menu.remove(menu_item) # Fill menu with new items group = [] for seat in seats: menu_item = Gtk.RadioMenuItem.new_with_label(group, str(seat[0])) group = menu_item.get_group() seat_menu.append(menu_item) if str(seat[0]) == selected_seat: menu_item.activate() menu_item.connect("activate", self.choose_seat, str(seat[0])) menu_item.show() # Process item choice def choose_seat(self, entry, seat_name): # Looks like this is called when item is deselected, too; must check if active if entry.get_active(): # This can either succeed or fail self.logind.AttachDevice(seat_name, '/sys'+self.device_syspath, True) Chosen RadioMenuItem gets marked irrespective of the choose_seat() execution result; and the only way to set marked item without triggering choose_seat() is to re-run update_seat_menu() with selected_seat argument, which is an overkill. I tried to connect choose_seat() with 'button-release-event' instead of 'activate' and call entry.activate() in choose_seat() if AttachDevice() succeeds, but this resulted in whole X desktop lockup until AttachDevice() timed out, and chosen item still got marked.

    Read the article

  • 'An error occurred. Please try later' message on Facebook authentication dialog

    - by Eugene Zhuang
    I am a newbie who is trying to create a Facebook app using PHP and Facebook's PHP SDK. The app is hosted on Heroku, and the sample app that they provided is working fine. However, I am now trying to get the sample app to work on Apache 2.2, and I have encountered a lot of problems along the way. Well, straight to the point, my latest problem will be trying to do Facebook login on localhost, but the 'An error occurred. Please try later' appears on the popup dialog. This does not happen on Heroku. Will someone please enlighten me on if there's any steps that I can take to overcome this error? I don't think it got to do with any coding error since I am just following the provided sample app. Thanks!

    Read the article

  • How to give position zero of spinner a prompt value?

    - by Eugene H
    The database is then transferring the data to a spinner which I want to leave position 0 blank so I can add a item to the spinner with no value making it look like a prompt. I have been going at it all day. FAil after Fail MainActivity public class MainActivity extends Activity { Button AddBtn; EditText et; EditText cal; Spinner spn; SQLController SQLcon; ProgressDialog PD; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AddBtn = (Button) findViewById(R.id.addbtn_id); et = (EditText) findViewById(R.id.et_id); cal = (EditText) findViewById(R.id.et_cal); spn = (Spinner) findViewById(R.id.spinner_id); spn.setOnItemSelectedListener(new OnItemSelectedListenerWrapper( new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { SQLcon.open(); Cursor c = SQLcon.readData(); if (c.moveToPosition(pos)) { String name = c.getString(c .getColumnIndex(DBhelper.MEMBER_NAME)); String calories = c.getString(c .getColumnIndex(DBhelper.KEY_CALORIES)); et.setText(name); cal.setText(calories); } SQLcon.close(); // closing database } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } })); SQLcon = new SQLController(this); // opening database SQLcon.open(); loadtospinner(); AddBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new MyAsync().execute(); } }); } public void loadtospinner() { ArrayList<String> al = new ArrayList<String>(); Cursor c = SQLcon.readData(); c.moveToFirst(); while (!c.isAfterLast()) { String name = c.getString(c.getColumnIndex(DBhelper.MEMBER_NAME)); String calories = c.getString(c .getColumnIndex(DBhelper.KEY_CALORIES)); al.add(name + ", Calories: " + calories); c.moveToNext(); } ArrayAdapter<String> aa1 = new ArrayAdapter<String>( getApplicationContext(), android.R.layout.simple_spinner_item, al); spn.setAdapter(aa1); // closing database SQLcon.close(); } private class MyAsync extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); PD = new ProgressDialog(MainActivity.this); PD.setTitle("Please Wait.."); PD.setMessage("Loading..."); PD.setCancelable(false); PD.show(); } @Override protected Void doInBackground(Void... params) { String name = et.getText().toString(); String calories = cal.getText().toString(); // opening database SQLcon.open(); // insert data into table SQLcon.insertData(name, calories); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); loadtospinner(); PD.dismiss(); } } } DataBase public class SQLController { private DBhelper dbhelper; private Context ourcontext; private SQLiteDatabase database; public SQLController(Context c) { ourcontext = c; } public SQLController open() throws SQLException { dbhelper = new DBhelper(ourcontext); database = dbhelper.getWritableDatabase(); return this; } public void close() { dbhelper.close(); } public void insertData(String name, String calories) { ContentValues cv = new ContentValues(); cv.put(DBhelper.MEMBER_NAME, name); cv.put(DBhelper.KEY_CALORIES, calories); database.insert(DBhelper.TABLE_MEMBER, null, cv); } public Cursor readData() { String[] allColumns = new String[] { DBhelper.MEMBER_ID, DBhelper.MEMBER_NAME, DBhelper.KEY_CALORIES }; Cursor c = database.query(DBhelper.TABLE_MEMBER, allColumns, null, null, null, null, null); if (c != null) { c.moveToFirst(); } return c; } } Helper public class DBhelper extends SQLiteOpenHelper { // TABLE INFORMATTION public static final String TABLE_MEMBER = "member"; public static final String MEMBER_ID = "_id"; public static final String MEMBER_NAME = "name"; public static final String KEY_CALORIES = "calories"; // DATABASE INFORMATION static final String DB_NAME = "MEMBER.DB"; static final int DB_VERSION = 2; // TABLE CREATION STATEMENT private static final String CREATE_TABLE = "create table " + TABLE_MEMBER + "(" + MEMBER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MEMBER_NAME + " TEXT NOT NULL," + KEY_CALORIES + " INT NOT NULL);"; public DBhelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBER); onCreate(db); } }

    Read the article

< Previous Page | 2 3 4 5 6 7 8  | Next Page >