Search Results

Search found 12222 results on 489 pages for 'initial context'.

Page 67/489 | < Previous Page | 63 64 65 66 67 68 69 70 71 72 73 74  | Next Page >

  • How to correctly populate records from SQLlite in ListActivity?

    - by Pavel
    Hi. Can someone please tell me how can I easily display every record from sqllite in ListActivity tab? I'm kinda confused with this. Do I have to create db from my helper class in TabActivity or ListActivity or both? My db helper class is as follow: package tabs.app; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DBAdapter { private static String DB_PATH = "/data/data/tabs.app/databases/"; public static final String KEY_ROWID = "_id"; public static final String KEY_LATITUDE = "latitude"; public static final String KEY_LONGITUDE = "longitude"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "coords"; private static final String DATABASE_TABLE = "coordsStorages"; private static final int DATABASE_VERSION = 2; /* private static final String DATABASE_CREATE = "create table coordsStorage (_id integer primary key autoincrement, latitude integer not null, longitude integer not null)"; */ public Context context; private DatabaseHelper DBHelper; private SQLiteDatabase db; public DBAdapter(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); } private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table coordsStorages (_id integer primary key autoincrement, latitude integer not null, longitude integer not null)"); } @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 titles"); onCreate(db); } } //---opens the database--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---closes the database--- public void close() { DBHelper.close(); } //---insert a title into the database--- public long insertCoords(int latitude, int longitude) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_LATITUDE, latitude); initialValues.put(KEY_LONGITUDE, longitude); return db.insert(DATABASE_TABLE, null, initialValues); } public void openDataBase() throws SQLException{ //Open the database String myPath = DB_PATH + DATABASE_NAME; db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } //---deletes a particular title--- public boolean deleteTitle(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //---retrieves all the titles--- public Cursor getAllTitles() { return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_LATITUDE, KEY_LONGITUDE}, null, null, null, null, null); } //---retrieves a particular title--- public Cursor getTitle(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_LATITUDE, KEY_LONGITUDE}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---updates a title--- /*public boolean updateTitle(long rowId, int latitude, int longitude) { ContentValues args = new ContentValues(); args.put(KEY_LATITUDE, latitude); args.put(KEY_LONGITUDE, longitude); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; }*/ } And Im trying to retrieve the records in TabActivity like this: public class Areas extends ListActivity { DBAdapter db; SimpleCursorAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.areas_layout); db = new DBAdapter(this); db.open(); Cursor c = db.getAllTitles(); startManagingCursor(c); String[] display = new String[] { db.KEY_LATITUDE }; int[] to = new int[] { R.id.row_latitude}; /* String[] display2 = new String[] { db.KEY_LONGITUDE }; int[] to2 = new int[] { R.id.row_longitude};*/ mAdapter = new SimpleCursorAdapter(this, R.layout.areas_layout, c, display, to); setListAdapter(mAdapter); /* mAdapter2 = new SimpleCursorAdapter(this, R.layout.areas_layout, c, display2, to2); setListAdapter(mAdapter2);*/ db.close(); } /* private void fillData() { // Get all of the rows from the database and create the item list Cursor c = db.getAllTitles(); startManagingCursor(c); }*/ } Whenever I'm trying to do that the error log outputs this: 06-07 09:51:56.529: ERROR/AndroidRuntime(2034): Uncaught handler: thread main exiting due to uncaught exception 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): java.lang.RuntimeException: Unable to start activity ComponentInfo{tabs.app/tabs.app.Areas}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list' 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2401) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.app.ActivityThread.startActivityNow(ActivityThread.java:2242) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:631) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.widget.TabHost.setCurrentTab(TabHost.java:317) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:127) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:346) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.view.View.performClick(View.java:2344) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.view.View.onTouchEvent(View.java:4133) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.view.View.dispatchTouchEvent(View.java:3672) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:850) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:882) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1712) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1202) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.app.Activity.dispatchTouchEvent(Activity.java:1987) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1696) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.view.ViewRoot.handleMessage(ViewRoot.java:1658) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.os.Handler.dispatchMessage(Handler.java:99) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.os.Looper.loop(Looper.java:123) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.app.ActivityThread.main(ActivityThread.java:4203) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at java.lang.reflect.Method.invokeNative(Native Method) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at java.lang.reflect.Method.invoke(Method.java:521) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at dalvik.system.NativeStart.main(Native Method) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list' 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.app.ListActivity.onContentChanged(ListActivity.java:236) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:316) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.app.Activity.setContentView(Activity.java:1620) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at tabs.app.Areas.onCreate(Areas.java:18) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364) 06-07 09:51:56.559: ERROR/AndroidRuntime(2034): ... 30 more 06-07 09:51:56.619: INFO/Process(51): Sending signal. PID: 2034 SIG: 3 06-07 09:51:56.619: INFO/dalvikvm(2034): threadid=7: reacting to signal 3 06-07 09:51:56.619: ERROR/dalvikvm(2034): Unable to open stack trace file '/data/anr/traces.txt': Permission denied Can someone please tell me what I'm doing wrong? Help greatly appreciated!

    Read the article

  • iPhone App Crashes when merging managed object contexts

    - by DVG
    Short Version: Using two managed object contexts, and while the context is saving to the store the application bombs when I attempt to merge the two contexts and reload the table view. Long Version: Okay, so my application is set up as thus. 3 view controllers, all table views. Platforms View Controller - Games View Controller (Predicated upon platform selection) - Add Game View Controller I ran into a problem when Games View Controller was bombing when adding a new entry to the context, because the fetched results contorller wanted to update the view for something that didn't match the predicate. As a solution, I rebuilt the Add Controller to use a second NSManagedObject Context, called adding context, following the design pattern in the Core Data Books example. My Games List View Controller is a delegate for the add controller, to handle all the saving, so my addButtonPressed method looks like this - (IBAction) addButtonPressed: (id) sender { AddGameTableViewController *addGameVC = [[AddGameTableViewController alloc] initWithNibName:@"AddGameTableViewController" bundle:nil]; NSManagedObjectContext *aAddingContext = [[NSManagedObjectContext alloc] init]; self.addingContext = aAddingContext; [aAddingContext release]; [addingContext setPersistentStoreCoordinator:[[gameResultsController managedObjectContext] persistentStoreCoordinator]]; addGameVC.context = addingContext; addGameVC.delegate = self; addGameVC.newGame = (Game *)[NSEntityDescription insertNewObjectForEntityForName:@"Game" inManagedObjectContext:addingContext]; UINavigationController *addNavCon = [[UINavigationController alloc] initWithRootViewController:addGameVC]; [self presentModalViewController:addNavCon animated:YES]; [addGameVC release]; [addNavCon release]; } There is also a delegate method which handles the saving. This all works swimmingly. The issue is getting the table view controller in the GameListViewController to update itself. Per the example, an observer is added to watch for the second context to be saved, and then to merge the addingContext with the primary one. So I have: - (void)addViewController:(AddGameTableViewController *)controller didFinishWithSave:(BOOL)save { if (save) { NSNotificationCenter *dnc = [NSNotificationCenter defaultCenter]; [dnc addObserver:self selector:@selector(addControllerContextDidSave:) name:NSManagedObjectContextDidSaveNotification object:addingContext]; //snip! Context Save Code [dnc removeObserver:self name:NSManagedObjectContextDidSaveNotification object:addingContext]; } self.addingContext = nil; [self dismissModalViewControllerAnimated:YES]; } - (void)addControllerContextDidSave:(NSNotification*)saveNotification { NSManagedObjectContext *myContext = [gameResultsController managedObjectContext]; [myContext mergeChangesFromContextDidSaveNotification:saveNotification]; } So now, what happens is after save is pressed, the application hangs for a moment and then crashes. The save is processed, as the new game is present when I relaunch the application, and the application seems to be flowing as appropriate, but it bombs out for reasons that are beyond my understanding. NSLog of the saveNotification spits out this: NSConcreteNotification 0x3b557f0 {name = NSManagingContextDidSaveChangesNotification; object = <NSManagedObjectContext: 0x3b4bb90>; userInfo = { inserted = {( <Game: 0x3b4f510> (entity: Game; id: 0x3b614e0 <x-coredata://13168366-B8E7-41C8-B384-BAF14A5E08D9/Game/p2> ; data: { name = "Final Fantasy XIII"; platform = 0x3b66910 <x-coredata://13168366-B8E7-41C8-B384-BAF14A5E08D9/Platform/p20>; }) )}; updated = {( <Platform: 0x3b67650> (entity: Platform; id: 0x3b66910 <x-coredata://13168366-B8E7-41C8-B384-BAF14A5E08D9/Platform/p20> ; data: { games = ( 0x3b614e0 <x-coredata://13168366-B8E7-41C8-B384-BAF14A5E08D9/Game/p2>, 0x603a530 <x-coredata://13168366-B8E7-41C8-B384-BAF14A5E08D9/Game/p1> ); name = "Xbox 360"; }) )}; }} I've tried both a simple [self.tableView reloadData]; and the more complicated multi-method table updating structure in the Core Data Books example. Both produce the same result.

    Read the article

  • android custom dialog imageButton onclicklistener

    - by Asaf Nevo
    this is my custom dialog class: package com.WhosAround.Dialogs; import com.WhosAround.AppVariables; import com.WhosAround.R; import com.WhosAround.AsyncTasks.LoadUserStatus; import com.WhosAround.Facebook.FacebookUser; import android.app.Dialog; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.MotionEvent; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; public class MenuFriend extends Dialog{ private FacebookUser friend; private AppVariables app; public MenuFriend(Context context, FacebookUser friend) { super(context, android.R.style.Theme_Translucent_NoTitleBar); this.app = (AppVariables) context.getApplicationContext(); this.friend = friend; } public void setDialog(String userName, Drawable userProfilePicture) { setContentView(R.layout.menu_friend); setCancelable(true); setCanceledOnTouchOutside(true); TextView name = (TextView) findViewById(R.id.menu_user_name); TextView status = (TextView) findViewById(R.id.menu_user_status); ImageView profilePicture = (ImageView) findViewById(R.id.menu_profile_picture); ImageButton closeButton = (ImageButton) findViewById(R.id.menu_close); name.setText(userName); profilePicture.setImageDrawable(userProfilePicture); if (friend.getStatus() != null) status.setText(friend.getStatus()); else new LoadUserStatus(app, friend, status).execute(0); closeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismiss(); } }) } } for some reason eclipse tells me the following errors on closeButton imageButton: The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new DialogInterface.OnClickListener(){}) The type new DialogInterface.OnClickListener(){} must implement the inherited abstract method DialogInterface.OnClickListener.onClick(DialogInterface, int) The method onClick(View) of type new DialogInterface.OnClickListener(){} must override or implement a supertype method why is that ?

    Read the article

  • Call Javascript method from .ashx file

    - by Prasad Jadhav
    From my previous question(Create json using JavaScriptSerializer), In .ashx file I am printing the json object using: context.Response.ContentType = "application/json"; context.Response.Write(json); I am calling this .ashx file from default.aspx which has some javascript function inside its <head> tag. My question is : How will I be able to call the javascript function from .ashx file after context.Response.Write(json);?

    Read the article

  • Detaching all entities of T to get fresh data

    - by Goran
    Lets take an example where there are two type of entites loaded: Product and Category, Product.CategoryId - Category.Id. We have available CRUD operations on products (not Categories). If on another screen Categories are updated (or from another user in the network), we would like to be able to reload the Categories, while preserving the context we currently use, since we could be in the middle of editing data, and we do not want changes to be lost (and we cannot depend on saving, since we have incomplete data). Since there is no easy way to tell EF to get fresh data (added, removed and modified), we thought of twp possible ways: 1) Getting products attached to context, and categories detached from context. This would mean that we loose the ability to access Product.Category.Name, which we do sometimes require, so we would need to manually resolve it (example when printing data). 2) detaching / attaching all Categories from current context. Context.ChangeTracker.Entries().Where(x => x.Entity.GetType() == typeof(T)).ForEach(x => x.State = EntityState.Detached); And then reload the categories, which will get fresh data. Do you find any problem with this second approach? We understand that this will require all constraints to be put on foreign keys, and not navigation properties, since when detaching all Categories, Product.Category navigation properties would be reset to null also. Also, there could be a potential performance problem, which we did not test, since there could be couple of thousand products loaded, and all would need to resolve navigation property when reloading. Which of the two do you prefer, and is there a better way (EF6 + .NET 4.0)?

    Read the article

  • Processing more than one button click at Android Widget

    - by dive
    Hi, all. I saw this topic and implement IntentService as describes, but what if I want more that one button? How can I distinguish button from each other? I'm trying to setFlags, but cannot read it at onHandleIntent() method: public static class UpdateService extends IntentService { ... @Override public void onHandleIntent(Intent intent) { ComponentName me = new ComponentName(this, ExampleProvider.class); AppWidgetManager manager = AppWidgetManager.getInstance(this); manager.updateAppWidget(me, buildUpdate(this)); } private RemoteViews buildUpdate(Context context) { RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.main_layout); Intent i = new Intent(this, ExampleProvider.class); PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0); updateViews.setOnClickPendingIntent(R.id.button_refresh, pi); i = new Intent(this, ExampleProvider.class); pi = PendingIntent.getBroadcast(context, 0, i, 0); updateViews.setOnClickPendingIntent(R.id.button_about, pi); return updateViews; } } At this little piece of code I have two PendingIntent linked with setOnClickPendingIntent, can I distinguish this intent for different actions and processing? Thanks for help

    Read the article

  • Using Apache Velocity with StringBuilders/CharSequences

    - by mindas
    We are using Apache Velocity for dynamic templates. At the moment Velocity has following methods for evaluation/replacing: public static boolean evaluate(Context context, Writer writer, String logTag, Reader reader) public static boolean evaluate(Context context, Writer out, String logTag, String instring) We use these methods by providing StringWriter to write evaluation results. Our incoming data is coming in StringBuilder format so we use StringBuilder.toString and feed it as instring. The problem is that our templates are fairly large (can be megabytes, tens of Ms on rare cases), replacements occur very frequently and each replacement operation triples the amount of required memory (incoming data + StringBuilder.toString() which creates a new copy + outgoing data). I was wondering if there is a way to improve this. E.g. if I could find a way to provide a Reader and Writer on top of same StringBuilder instance that only uses extra memory for in/out differences, would that be a good approach? Has anybody done anything similar and could share any source for such a class? Or maybe there any better solutions to given problem?

    Read the article

  • android.R.layout.simple_list_item_checked not toggling in ListView

    - by Mohit Deshpande
    Here is my custom adapter: ... @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(context); View v = inflater.inflate(android.R.layout.simple_list_item_checked, parent, false); return v; } ... Now this visually appears to be exactly what I needed. The problem is that I can't get toggle the checked state when I click on the listview item. Any solutions?

    Read the article

  • ASP.NET MVC: Can't figure out what VirtualPath is?

    - by Ryan_Pitts
    I have a View that displays a list of images and i am now trying to get it to display the images as thumbnails. Well, i'm pretty sure i got most of it right using VirtualPath's from a custom ActionResult although i can't seem to figure out what it is making the VirtualPath url?? BTW, i'm using XML to store the data from the images instead of SQL. Here is my code: Code from my custom ActionResult: public class ThumbnailResult : ActionResult { public ThumbnailResult(string virtualPath) { this.VirtualPath = virtualPath; } public string VirtualPath { get; set; } public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.ContentType = "image/bmp"; string fullFileName = context.HttpContext.Server.MapPath("~/Galleries/WhereConfusionMeetsConcrete/" + VirtualPath); using (System.Drawing.Image photoImg = System.Drawing.Image.FromFile(fullFileName)) { using (System.Drawing.Image thumbPhoto = photoImg.GetThumbnailImage(100, 100, null, new System.IntPtr())) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { thumbPhoto.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); context.HttpContext.Response.BinaryWrite(ms.ToArray()); context.HttpContext.Response.End(); } } } } } Code for my Controller: public ActionResult Thumbnail(string id) { return new ThumbnailResult(id); } Code for my View: <% foreach (var image in ViewData.Model) { %> <a href="../Galleries/TestGallery1/<%= image.Path %>"><img src="../Galleries/TestGallery1/thumbnail/<%= image.Path %>" alt="<%= image.Caption %>" /></a> <br /><br /><%= image.Caption %><br /><br /><br /> <% } %> Any help would be greatly appreciated!! Let me know of any questions you have as well. :) Thanks!

    Read the article

  • How to implement a TypeConverter for a type and property I don't own?

    - by CannibalSmith
    This is annoying: <GeometryDrawing> <GeometryDrawing.Pen> <Pen Brush="Black"/> </GeometryDrawing.Pen> </GeometryDrawing> I want this: <GeometryDrawing Pen="Black"/> So I write a TypeConverter: public class PenConverter : TypeConverter { static readonly BrushConverter brushConverter = new BrushConverter(); public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { var s = value as string; if (a != null) { var brush = brushConverter.ConvertFromInvariantString(s) as Brush; return new Pen(brush, 1); } return base.ConvertFrom(context, culture, value); } } Now, how do I link it up with the Pen type? I can't just add a TypeConverterAttribute to it as I don't own it (nor do I own GeometryDrawing.Pen property).

    Read the article

  • iPhone: Create a single UIView from multiple clicks

    - by Cuzog
    I'm making a partial overlay modal in my app with the code from “Semi-Modal (Transparent) Dialogs on the iPhone” at ramin.firoozye.com. In doing so, the button that calls the modal is still visible and clickable. I will hide this button when the modal spawns, but I want to be sure if the user clicks very quickly twice, a new modal doesn't come up for each click. What is the best way to check that the modal doesn't already exist when calling it from the button click? You can download the test project here. For those that don't have xcode, the relevant functions are below: I call forth the modal on button click with this: - (IBAction)displayModal:(id)sender { ModalViewController *modalController = [[ModalViewController alloc] initWithNibName:@"ModalViewController" bundle:nil]; modalController.view.frame = CGRectOffset(modalController.view.frame, 0, 230); [self showModal:modalController.view]; } Then use this function to animate the custom modal over the current view: - (void)showModal:(UIView*) modalView { UIWindow* mainWindow = (((TestAppDelegate*) [UIApplication sharedApplication].delegate).window); CGPoint middleCenter = modalView.center; CGSize offSize = [UIScreen mainScreen].bounds.size; CGPoint offScreenCenter = CGPointMake(offSize.width / 2.0, offSize.height * 1.5); modalView.center = offScreenCenter; // we start off-screen [mainWindow addSubview:modalView]; // Show it with a transition effect [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.4]; // animation duration in seconds modalView.center = middleCenter; [UIView commitAnimations]; } Then I dismiss the modal on button click with this: - (IBAction)dismissModal:(id)sender { [self hideModal:self.view]; } And then use these functions to animate the modal offscreen and clean itself up: - (void)hideModal:(UIView*) modalView { CGSize offSize = [UIScreen mainScreen].bounds.size; CGPoint offScreenCenter = CGPointMake(offSize.width / 2.0, offSize.height * 1.5); [UIView beginAnimations:nil context:modalView]; [UIView setAnimationDuration:0.7]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(hideModalEnded:finished:context:)]; modalView.center = offScreenCenter; [UIView commitAnimations]; } - (void)hideModalEnded:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context { UIView* modalView = (UIView *)context; [modalView removeFromSuperview]; [self release]; } Any help is greatly appreciated!

    Read the article

  • Android-Close Other Apps

    - by Luke
    I have some code that will launch a different application using intents but what can I do to close or kill the other app? Here is the launch code (works great): Intent i = new Intent(); i.setAction(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_LAUNCHER); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.setComponent( new ComponentName(resolveInfo.activityInfo.applicationInfo.packageName, resolveInfo.activityInfo.name)); I tried to kill the background processes but no luck: ActivityManager activityManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE); activityManager.killBackgroundProcesses("com.pandora.android"); I also tried this to kill it: context.stopService(new Intent(context, Class.forName("com.bla.bla")));

    Read the article

  • how can I use internal resource (e.g. R.id.myImage01) as an email attachment?

    - by Azam
    how can I use internal resource (e.g. R.drawable.myImage01) as an email attachment? I tried the following code. It shows the file is attach but actually the email gets send without any attachment. Context context = getApplicationContext(); String imagePath = context.getFilesDir() + "/" + "myImage01.png"; emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, Uri.parse(imagePath)); Thanks Azam

    Read the article

  • How not to abort http response c#

    - by user194076
    I need to run several methods after sending file to a user for a download. What happens is that after I send a file to a user, response is aborted and I can no longer do anything after response.end(). for example, this is my sample code: Response.Clear(); Response.AddHeader("content-disposition", "attachment; filename=test.pdf"); Response.ContentType = "application/pdf"; byte[] a = System.Text.Encoding.UTF8.GetBytes("test"); Response.BinaryWrite(a); Response.End(); StartNextMethod(); Response.Redirect(URL); So, in this example StartNextMethod and Response.Redirect are not executing. What I tried is I created a separate handler(ashx) with the following code: public void ProcessRequest(HttpContext context) { context.Response.Clear(); context.Response.AddHeader("content-disposition", "attachment; filename=test.pdf"); context.Response.ContentType = "application/pdf"; byte[] a = System.Text.Encoding.UTF8.GetBytes("test"); context.Response.BinaryWrite(a); context.Response.End(); } and call it like this: Download d = new Download(); d.ProcessRequest(HttpContext.Current); StartNextMethod(); Response.Redirect(URL); but the same error happen. I've tryied to replace Response.End with CompleteRequest but it doesn't help. I guess the problem is that I'm using HttpContext.Current but should use a separate response stream. Is that correct? how do I do that in a separate method generically (Assume that I want my handler to accept byte array of data and content type and be downloadable from a separate response. I really do not want to use a separate page for a response. UPDATE I still didn't find a good solution. I'd like to do some actions after user has downloaded a file, but without using a separate page for a response\request thing.

    Read the article

  • Basic drawing with Quartz 2D on iPhone

    - by wwrob
    My goal is to make a program that will draw points whenever the screen is touched. This is what I have so far: The header file: #import <UIKit/UIKit.h> @interface ElSimView : UIView { CGPoint firstTouch; CGPoint lastTouch; UIColor *pointColor; CGRect *points; int npoints; } @property CGPoint firstTouch; @property CGPoint lastTouch; @property (nonatomic, retain) UIColor *pointColor; @property CGRect *points; @property int npoints; @end The implementation file: //@synths etc. - (id)initWithFrame:(CGRect)frame { return self; } - (id)initWithCoder:(NSCoder *)coder { if(self = [super initWithCoder:coder]) { self.npoints = 0; } return self; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; firstTouch = [touch locationInView:self]; lastTouch = [touch locationInView:self]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; lastTouch = [touch locationInView:self]; points = (CGRect *)malloc(sizeof(CGRect) * ++npoints); points[npoints-1] = CGRectMake(lastTouch.x-15, lastTouch.y-15,30,30); [self setNeedsDisplay]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; lastTouch = [touch locationInView:self]; [self setNeedsDisplay]; } - (void)drawRect:(CGRect)rect { CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetLineWidth(context, 2.0); CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor); CGContextSetFillColorWithColor(context, pointColor.CGColor); for(int i=0; i<npoints; i++) CGContextAddEllipseInRect(context, points[i]); CGContextDrawPath(context, kCGPathFillStroke); } - (void)dealloc { free(points); [super dealloc]; } @end When I load this and click some points, it draws the first points normally, then then next points are drawn along with random ellipses (not even circles). Also I have another question: When is exactly drawRect executed?

    Read the article

  • Trying to start a service on boot on Android

    - by Alex
    I've been trying to start a service when a device boots up on android, but I cannot get it to work. I've looked a number of links online but none of the code is working. Am I forgetting something? This is my code. Manifest <receiver android:name=".StartServiceAtBootReceiver" android:enabled="true" android:exported="false" android:label="StartServiceAtBootReceiver"> <intent-filter> <action android:name="android.intent.action._BOOT_COMPLETED"/> </intent-filter> </receiver> <service android:enabled="true" android:name="com.test.RunService"/> Receiver OnReceive public void onReceive(Context context, Intent intent) { if("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) { Intent serviceLauncher = new Intent(context, RunService.class); context.startService(serviceLauncher); Log.v("TEST", "Service loaded at start"); } } Thanks,

    Read the article

  • is it better to test if a function is needed inside or outside of it?

    - by b0x0rz
    what is the best practice? call a function then return if you test for something, or test for something then call? i prefer the test inside of function because it makes an easier viewing of what functions are called. for example: protected void Application_BeginRequest(object sender, EventArgs e) { this.FixURLCosmetics(); } and private void FixURLCosmetics() { HttpContext context = HttpContext.Current; if (!context.Request.HttpMethod.ToString().Equals("GET", StringComparison.OrdinalIgnoreCase)) { // if not a GET method cancel url cosmetics return; }; string url = context.Request.RawUrl.ToString(); bool doRedirect = false; // remove > default.aspx if (url.EndsWith("/default.aspx", StringComparison.OrdinalIgnoreCase)) { url = url.Substring(0, url.Length - 12); doRedirect = true; } // remove > www if (url.Contains("//www")) { url = url.Replace("//www", "//"); doRedirect = true; } // redirect if necessary if (doRedirect) { context.Response.Redirect(url); } } is this good: if (!context.Request.HttpMethod.ToString().Equals("GET", StringComparison.OrdinalIgnoreCase)) { // if not a GET method cancel url cosmetics return; }; or should that test be done in Application_BeginRequest? what is better? thnx

    Read the article

  • Copy Rows in a One to Many with LINQ (2 SQL)

    - by Refracted Paladin
    I have a table that stores a bunch of diagnosis for a single plan. When the users create a new plan I need to copy over all existing diagnosis's as well. I had thought to try the below but this is obviously not correct. I am guessing that I will need to loop through my oldDiagnosis part, but how? Thanks! My Attempt so far... public static void CopyPlanDiagnosis(int newPlanID, int oldPlanID) { using (var context = McpDataContext.Create()) { var oldDiagnosis = from planDiagnosi in context.tblPlanDiagnosis where planDiagnosi.PlanID == oldPlanID select planDiagnosi; var newDiagnosis = new tblPlanDiagnosi { PlanID = newPlanID, DiagnosisCueID = oldDiagnosis.DiagnosisCueID, DiagnosisOther = oldDiagnosis.DiagnosisOther, AdditionalInfo = oldDiagnosis.AdditionalInfo, rowguid = Guid.NewGuid() }; context.tblPlanDiagnosis.InsertOnSubmit(newDiagnosis); context.SubmitChanges(); } }

    Read the article

  • Field Members vs Method Variables?

    - by Braveyard
    Recently I've been thinking about performance difference between class field members and method variables. What exactly I mean is in the example below : Lets say we have a DataContext object for Linq2SQL class DataLayer { ProductDataContext context = new ProductDataContext(); public IQueryable<Product> GetData() { return context.Where(t=>t.ProductId == 2); } } In the example above, context will be stored in heap and the GetData method variables will be removed from Stack after Method is executed. So lets examine the following example to make a distinction : class DataLayer { public IQueryable<Product> GetData() { ProductDataContext context = new ProductDataContext(); return context.Where(t=>t.ProductId == 2); } } (*1) So okay first thing we know is if we define ProductDataContext instance as a field, we can reach it everywhere in the class which means we don't have to create same object instance all the time. But lets say we are talking about Asp.NET and once the users press submit button the post data is sent to the server and the events are executed and the posted data stored in a database via the method above so it is probable that the same user can send different data after one another.If I know correctly after the page is executed, the finalizers come into play and clear things from memory (from heap) and that means we lose our instance variables from memory as well and after another post, DataContext should be created once again for the new page cycle. So it seems the only benefit of declaring it publicly to the whole class is the just number one text above. Or is there something other? Thanks in advance... (If I told something incorrect please fix me.. )

    Read the article

  • How to make command-line options mandatory with GLib?

    - by ahe
    I use GLib to parse some command-line options. The problem is that I want to make two of those options mandatory so that the program terminates with the help screen if the user omits them. My code looks like this: static gint line = -1; static gint column = -1; static GOptionEntry options[] = { {"line", 'l', 0, G_OPTION_ARG_INT, &line, "The line", "L"}, {"column", 'c', 0, G_OPTION_ARG_INT, &column, "The column", "C"}, {NULL} }; ... int main(int argc, char** argv) { GError *error = NULL; GOptionContext *context; context = g_option_context_new ("- test"); g_option_context_add_main_entries (context, options, NULL); if (!g_option_context_parse(context, &argc, &argv, &error)) { usage(error->message, context); } ... return 0; } If I omit one of those parameters or both on the command-line g_option_context_parse() still succeeds and the values in question (line and or column) are still -1. How can I tell GLib to fail parsing if the user doesn't pass both options on the command-line? Maybe I'm just blind but I couldn't find a flag I can put into my GOptionEntry data structure to tell it to make those fields mandatory. Of course I could check if one of those variables is still -1 but then the user could just have passed this value on the command-line and I want to print a separate error message if the values are out of range.

    Read the article

  • How to manage lifecycle in a ViewGroup-derived class?

    - by Scott Smith
    I had a bunch of code in an activity that displays a running graph of some external data. As the activity code was getting kind of cluttered, I decided to extract this code and create a GraphView class: public class GraphView extends LinearLayout { public GraphView(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.graph_view, this, true); } public void start() { // Perform initialization (bindings, timers, etc) here } public void stop() { // Unbind, destroy timers, yadda yadda } . . . } Moving stuff into this new LinearLayout-derived class was simple. But there was some lifecycle management code associated with creating and destroying timers and event listeners used by this graph (I didn't want this thing polling in the background if the activity was paused, for example). Coming from a MS Windows background, I kind of expected to find overridable onCreate() and onDestroy() methods or something similar, but I haven't found anything of the sort in LinearLayout (or any of its inherited members). Having to leave all of this initialization code in the Activity, and then having to pass it into the view seemed like it defeated the original purpose of encapsulating all of this code into a reusable view. I ended up adding two additional public methods to my view: start() and stop(). I make these calls from the activity's onResume() and onPause() methods respectively. This seems to work, but it feels like I'm using duct tape here. Does anyone know how this is typically done? I feel like I'm missing something...

    Read the article

  • custom helpers inside each block

    - by Unspecified
    myArray = [{name: "name1", age: 20}, {name: "name2", age:22}]; {{#each person in myArray}} {{#myHelper person}} Do something {{/myHelper}} {{/each}} Handlebars.registerHelper(function(context, options){ if(context.age > 18){ return options.fn(this); }else{ return options.inverse(this); } }) In the above code when I tried to debug my custom helper it shows the context="person" while I want the context to be the person object, what's wrong with my code ? I found a similar question here but did not get it either...

    Read the article

  • Need Help with .NET OpenId HttpHandler

    - by Mark E
    I'm trying to use a single HTTPHandler to authenticate a user's open id and receive a claimresponse. The initial authentication works, but the claimresponse does not. The error I receive is "This webpage has a redirect loop." What am I doing wrong? public class OpenIdLogin : IHttpHandler { private HttpContext _context = null; public void ProcessRequest(HttpContext context) { _context = context; var openid = new OpenIdRelyingParty(); var response = openid.GetResponse(); if (response == null) { // Stage 2: user submitting Identifier openid.CreateRequest(context.Request.Form["openid_identifier"]).RedirectToProvider(); } else { // Stage 3: OpenID Provider sending assertion response switch (response.Status) { case AuthenticationStatus.Authenticated: //FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, false); string identifier = response.ClaimedIdentifier; //****** TODO only proceed if we don't have the user's extended info in the database ************** ClaimsResponse claim = response.GetExtension<ClaimsResponse>(); if (claim == null) { //IAuthenticationRequest req = openid.CreateRequest(identifier); IAuthenticationRequest req = openid.CreateRequest(Identifier.Parse(identifier)); var fields = new ClaimsRequest(); fields.Email = DemandLevel.Request; req.AddExtension(fields); req.RedirectingResponse.Send(); //Is this correct? } else { context.Response.ContentType = "text/plain"; context.Response.Write(claim.Email); //claim.FullName; } break; case AuthenticationStatus.Canceled: //TODO break; case AuthenticationStatus.Failed: //TODO break; } } }

    Read the article

  • How To Join Tables from Two Different Contexts with LINQ2SQL?

    - by RSolberg
    I have 2 data contexts in my application (different databases) and need to be able to query a table in context A with a right join on a table in context B. How do I go about doing this in LINQ2SQL? Why?: We are using a SaaS product for tracking our time, projects, etc. and would like to send new service requests to this product to prevent our team from duplicating data entry. Context A: This db stores service request information. It is a third party DB and we are not able to make changes to the structure of this DB as it could have unintended non-supportable consequences downstream. Context B: This data stores the "log" data of service requests that have been processed. My team and I have full control over this DB's structure, etc. Unprocessed service requests should find their way into this DB and another process will identify it as not being processed and send the record to the SaaS product. This is the query that I am looking to modify. I was able to do a !list.Contains(c.swHDCaseId) initially, but this cannot handle more than 2100 items. Is there a way to add a join to the other context? var query = (from c in contextA.Cases where monitoredInboxList.Contains(c.INBOXES.inboxName) select new { //setup fields here... });

    Read the article

  • MVC C# Controller Method to return Tables

    - by Rob Tiu
    I'm a real beginner with MVC and my issue is this, I have a mdf database with multiple tables and I want to have a method return "ANY" table from the database and pass it to a aspx view. Examples of other tables in the database: Articles, Products, Supplies Here is an example of my code to view an Article Table from the database: //USING LINQ-SQL CONTEXT DATABASE public ActionResult ArticlePage() { tinypeas_db_contextDataContext context = HttpContext.Application["context"] as tinypeas_db_contextDataContext; try { return View(context.Articles); } catch { return Json(false, JsonRequestBehavior.AllowGet); } } How would I modify this method to dynamically pass any table to the view? Or should I be using something else other than Linq-to-SQL

    Read the article

< Previous Page | 63 64 65 66 67 68 69 70 71 72 73 74  | Next Page >