Search Results

Search found 1255 results on 51 pages for 'todo'.

Page 3/51 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • How to move sub-headings to under other headings in emacs org-mode

    - by Mittenchops
    My list looks like this: * TODAY ** TODO Item 1 ** TODO Item 2 * TOMORROW ** TODO Item 3 ** TODO Item 4 ...as a single list, based on some advice I received here. I'd like to move TODO Item 2 from under TODAY to under TOMORROW. The manual says: M-up M-down Move the item including subitems up/down (swap with previous/next item of same indentation). If the list is ordered, renumbering is automatic. But while I can change the places of Item 1 and Item 2, I cannot move Item 2 outside of the Today heading---I cannot move it down under TOMORROW to proceed Item 3. The buffer tells me: cannot move past superior level or buffer limit org mode What is the keystroke that lets me move sub-items "past superior level" to under new headings?

    Read the article

  • Handling file upload in a non-blocking manner

    - by Kaliyug Antagonist
    The background thread is here Just to make objective clear - the user will upload a large file and must be redirected immediately to another page for proceeding different operations. But the file being large, will take time to be read from the controller's InputStream. So I unwillingly decided to fork a new Thread to handle this I/O. The code is as follows : The controller servlet /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("In Controller.doPost(...)"); TempModel tempModel = new TempModel(); tempModel.uploadSegYFile(request, response); System.out.println("Forwarding to Accepted.jsp"); /*try { Thread.sleep(1000 * 60); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ request.getRequestDispatcher("/jsp/Accepted.jsp").forward(request, response); } The model class package com.model; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.utils.ProcessUtils; public class TempModel { public void uploadSegYFile(HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub System.out.println("In TempModel.uploadSegYFile(...)"); /* * Trigger the upload/processing code in a thread, return immediately * and notify when the thread completes */ try { FileUploaderRunnable fileUploadRunnable = new FileUploaderRunnable( request.getInputStream()); /* * Future<FileUploaderRunnable> future = ProcessUtils.submitTask( * fileUploadRunnable, fileUploadRunnable); * * FileUploaderRunnable processed = future.get(); * * System.out.println("Is file uploaded : " + * processed.isFileUploaded()); */ Thread uploadThread = new Thread(fileUploadRunnable); uploadThread.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /* * catch (InterruptedException e) { // TODO Auto-generated catch block * e.printStackTrace(); } catch (ExecutionException e) { // TODO * Auto-generated catch block e.printStackTrace(); } */ System.out.println("Returning from TempModel.uploadSegYFile(...)"); } } The Runnable package com.model; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; public class FileUploaderRunnable implements Runnable { private boolean isFileUploaded = false; private InputStream inputStream = null; public FileUploaderRunnable(InputStream inputStream) { // TODO Auto-generated constructor stub this.inputStream = inputStream; } public void run() { // TODO Auto-generated method stub /* Read from InputStream. If success, set isFileUploaded = true */ System.out.println("Starting upload in a thread"); File outputFile = new File("D:/06c01_output.seg");/* * This will be changed * later */ FileOutputStream fos; ReadableByteChannel readable = Channels.newChannel(inputStream); ByteBuffer buffer = ByteBuffer.allocate(1000000); try { fos = new FileOutputStream(outputFile); while (readable.read(buffer) != -1) { fos.write(buffer.array()); buffer.clear(); } fos.flush(); fos.close(); readable.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("File upload thread completed"); } public boolean isFileUploaded() { return isFileUploaded; } } My queries/doubts : Spawning threads manually from the Servlet makes sense to me logically but scares me coding wise - the container isn't aware of these threads after all(I think so!) The current code is giving an Exception which is quite obvious - the stream is inaccessible as the doPost(...) method returns before the run() method completes : In Controller.doPost(...) In TempModel.uploadSegYFile(...) Returning from TempModel.uploadSegYFile(...) Forwarding to Accepted.jsp Starting upload in a thread Exception in thread "Thread-4" java.lang.NullPointerException at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:512) at org.apache.coyote.http11.InternalInputBuffer.fill(InternalInputBuffer.java:497) at org.apache.coyote.http11.InternalInputBuffer$InputStreamInputBuffer.doRead(InternalInputBuffer.java:559) at org.apache.coyote.http11.AbstractInputBuffer.doRead(AbstractInputBuffer.java:324) at org.apache.coyote.Request.doRead(Request.java:422) at org.apache.catalina.connector.InputBuffer.realReadBytes(InputBuffer.java:287) at org.apache.tomcat.util.buf.ByteChunk.substract(ByteChunk.java:407) at org.apache.catalina.connector.InputBuffer.read(InputBuffer.java:310) at org.apache.catalina.connector.CoyoteInputStream.read(CoyoteInputStream.java:202) at java.nio.channels.Channels$ReadableByteChannelImpl.read(Unknown Source) at com.model.FileUploaderRunnable.run(FileUploaderRunnable.java:39) at java.lang.Thread.run(Unknown Source) Keeping in mind the point 1., does the use of Executor framework help me in anyway ? package com.utils; import java.util.concurrent.Future; import java.util.concurrent.ScheduledThreadPoolExecutor; public final class ProcessUtils { /* Ensure that no more than 2 uploads,processing req. are allowed */ private static final ScheduledThreadPoolExecutor threadPoolExec = new ScheduledThreadPoolExecutor( 2); public static <T> Future<T> submitTask(Runnable task, T result) { return threadPoolExec.submit(task, result); } } So how should I ensure that the user doesn't block and the stream remains accessible so that the (uploaded)file can be read from it?

    Read the article

  • C# unit test code questions continue

    - by 5YrsLaterDBA
    more questions after questions in here: http://stackoverflow.com/questions/2714073/c-unit-test-code-questions I found the VS unit test testframe treat private and protected method in the same way but deferent with public method. The following is the generated code for a private method: /// <summary> ///A test for recordLogin ///</summary> [TestMethod()] [DeploymentItem("SystemSoftware.exe")] public void recordLoginTest() { User_Accessor target = new User_Accessor(); // TODO: Initialize to an appropriate value Guid userId = new Guid(); // TODO: Initialize to an appropriate value string action = string.Empty; // TODO: Initialize to an appropriate value Users user = null; // TODO: Initialize to an appropriate value AndeDBEntities db = null; // TODO: Initialize to an appropriate value bool expected = false; // TODO: Initialize to an appropriate value bool actual; actual = target.recordLogin(userId, action, user, db); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); } questions: [DeploymentItem("SystemSoftware.exe")] is for private and protected methods, why needs it and what is it for? In my original class/file, if I point to the original method and try to "Find All References". The reference in the unit test class/file will not show up for private and protected methods but it will show up for all public methods. Why is that? Is it right? 3.

    Read the article

  • read text file from phone memory in android

    - by Sudhakar
    Hi..I just wanna create a text file into phone memory and have to read its content to display.Now i created a text file.But its not present in the path data/data/package-name/file name.txt & it didn't display the content on emulator. My code is.. public class PhonememAct extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv=(TextView)findViewById(R.id.tv); FileOutputStream fos = null; try { fos = openFileOutput("Test.txt", Context.MODE_PRIVATE); } catch (FileNotFoundException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } try { fos.write("Hai..".getBytes()); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } FileInputStream fis = null; try { fis = openFileInput("Test.txt"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } int c; try { while((c=fis.read())!=-1) { tv.setText(c); setContentView(tv); //k += (char)c; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Thanks in adv.

    Read the article

  • Attaching event on the fly with prototype

    - by andreas
    Hi, I've been scratching my head over this for an hour... I have a list of todo which has done button on each item. Every time a user clicks on that, it's supposed to do an Ajax call to the server, calling the marking function then updates the whole list. The problem I'm facing is that the new list has done buttons as well on each item. And it doesn't attach the click event anymore after first update. How do you attach an event handler on newly updated element with prototype? Note: I've passed evalScripts: true to the updater wrapper initial event handler attach <script type="text/javascript"> document.observe('dom:loaded', function() { $$('.todo-done a').each(function(a) { $(a).observe('click', function(e) { var todoId = $(this).readAttribute('href').substr(1); new Ajax.Updater('todo-list', $.utils.getPath('/todos/ajax_mark/done'), { onComplete: function() { $.utils.updateList({evalScripts: true}); } }); }); }) }); </script> updateList: <script type="text/javascript"> var Utils = Class.create({ updateList: function(options) { if(typeof options == 'undefined') { options = {}; } new Ajax.Updater('todo-list', $.utils.getPath('/todos/ajax_get'), $H(options).merge({ onComplete: function() { $first = $('todo-list').down(); $first.hide(); Effect.Appear($first, {duration: 0.7}); new Effect.Pulsate($('todo-list').down(), {pulses: 1, duration: 0.4, queue: 'end'}); } }) ); } }) $.utils = new Utils('globals'); </script> any help is very much appreciated, thank you :)

    Read the article

  • Backbone.js Collection Iteration Using .each()

    - by the_archer
    I've been doing some Backbone.js coding and have come across a particular problem where I am having trouble iterating over the contents of a collection. The line Tasker_TodoList.each(this.addOne, this);in the addAll function in AppView is not executing properly for some reason, throwing the error: Uncaught TypeError: undefined is not a function the code in question is: $(function() { var Todo = Backbone.Model.extend({ defaults: { title: "Some Title...", status: 0 //not completed } }); var TodoList = Backbone.Collection.extend({ model: Todo, localStorage: new Store('tasker') }); var Tasker_TodoList = new TodoList(); var TodoView = Backbone.View.extend({ tagName: 'li', template: _.template($('#todoTemplate').html()), events: { 'click .delbtn': 'delTodo' }, initialize: function(){ console.log("a new todo initialized"); //this.model.on('change', this.render, this); }, render: function(){ this.$el.html(this.template(this.model.toJSON())); return this; }, delTodo: function(){ console.log("deleted todo"); } }); var AppView = Backbone.View.extend({ el: 'body', events: { 'click #addBtn': 'createOnClick' }, initialize: function(){ Tasker_TodoList.fetch(); Tasker_TodoList.on('add', this.addAll); console.log(Tasker_TodoList); }, addAll: function(){ $('#tasksList').html(''); console.log("boooooooma"); Tasker_TodoList.each(this.addOne, this); }, addOne: function(todo){ console.log(todo); }, createOnClick: function(){ Tasker_TodoList.create(); } }); var Tasker = new AppView(); }); can somebody help me in finding out what I am doing wrong? Thank you all for your help :-)

    Read the article

  • function to org-sort by three (3) criteria: due date / priority / title

    - by lawlist
    Is anyone aware of an org-sort function / modification that can refile / organize a group of TODO so that it sorts them by three (3) criteria: first sort by due date, second sort by priority, and third sort by by title of the task? EDIT: If anyone can please help me to modify this so that undated TODO are sorted last, that would be greatly appreciated -- at the present time, undated TODO are not being sorted: ;; multiple sort (defun org-sort-multi (&rest sort-types) "Multiple sorts on a certain level of an outline tree, or plain list items. SORT-TYPES is a list where each entry is either a character or a cons pair (BOOL . CHAR), where BOOL is whether or not to sort case-sensitively, and CHAR is one of the characters defined in `org-sort-entries-or-items'. Entries are applied in back to front order. Example: To sort first by TODO status, then by priority, then by date, then alphabetically (case-sensitive) use the following call: (org-sort-multi '(?d ?p ?t (t . ?a)))" (interactive) (dolist (x (nreverse sort-types)) (when (char-valid-p x) (setq x (cons nil x))) (condition-case nil (org-sort-entries (car x) (cdr x)) (error nil)))) ;; sort current level (defun lawlist-sort (&rest sort-types) "Sort the current org level. SORT-TYPES is a list where each entry is either a character or a cons pair (BOOL . CHAR), where BOOL is whether or not to sort case-sensitively, and CHAR is one of the characters defined in `org-sort-entries-or-items'. Entries are applied in back to front order. Defaults to \"?o ?p\" which is sorted by TODO status, then by priority" (interactive) (when (equal mode-name "Org") (let ((sort-types (or sort-types (if (or (org-entry-get nil "TODO") (org-entry-get nil "PRIORITY")) '(?d ?t ?p) ;; date, time, priority '((nil . ?a)))))) (save-excursion (outline-up-heading 1) (let ((start (point)) end) (while (and (not (bobp)) (not (eobp)) (<= (point) start)) (condition-case nil (outline-forward-same-level 1) (error (outline-up-heading 1)))) (unless (> (point) start) (goto-char (point-max))) (setq end (point)) (goto-char start) (apply 'org-sort-multi sort-types) (goto-char end) (when (eobp) (forward-line -1)) (when (looking-at "^\\s-*$") ;; (delete-line) ) (goto-char start) ;; (dotimes (x ) (org-cycle)) )))))

    Read the article

  • Metro: Understanding the default.js File

    - by Stephen.Walther
    The goal of this blog entry is to describe — in painful detail — the contents of the default.js file in a Metro style application written with JavaScript. When you use Visual Studio to create a new Metro application then you get a default.js file automatically. The file is located in a folder named \js\default.js. The default.js file kicks off all of your custom JavaScript code. It is the main entry point to a Metro application. The default contents of the default.js file are included below: // For an introduction to the Blank template, see the following documentation: // http://go.microsoft.com/fwlink/?LinkId=232509 (function () { "use strict"; var app = WinJS.Application; app.onactivated = function (eventObject) { if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) { if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) { // TODO: This application has been newly launched. Initialize // your application here. } else { // TODO: This application has been reactivated from suspension. // Restore application state here. } WinJS.UI.processAll(); } }; app.oncheckpoint = function (eventObject) { // TODO: This application is about to be suspended. Save any state // that needs to persist across suspensions here. You might use the // WinJS.Application.sessionState object, which is automatically // saved and restored across suspension. If you need to complete an // asynchronous operation before your application is suspended, call // eventObject.setPromise(). }; app.start(); })(); There are several mysterious things happening in this file. The purpose of this blog entry is to dispel this mystery. Understanding the Module Pattern The first thing that you should notice about the default.js file is that the entire contents of this file are enclosed within a self-executing JavaScript function: (function () { ... })(); Metro applications written with JavaScript use something called the module pattern. The module pattern is a common pattern used in JavaScript applications to create private variables, objects, and methods. Anything that you create within the module is encapsulated within the module. Enclosing all of your custom code within a module prevents you from stomping on code from other libraries accidently. Your application might reference several JavaScript libraries and the JavaScript libraries might have variables, objects, or methods with the same names. By encapsulating your code in a module, you avoid overwriting variables, objects, or methods in the other libraries accidently. Enabling Strict Mode with “use strict” The first statement within the default.js module enables JavaScript strict mode: 'use strict'; Strict mode is a new feature of ECMAScript 5 (the latest standard for JavaScript) which enables you to make JavaScript more strict. For example, when strict mode is enabled, you cannot declare variables without using the var keyword. The following statement would result in an exception: hello = "world!"; When strict mode is enabled, this statement throws a ReferenceError. When strict mode is not enabled, a global variable is created which, most likely, is not what you want to happen. I’d rather get the exception instead of the unwanted global variable. The full specification for strict mode is contained in the ECMAScript 5 specification (look at Annex C): http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf Aliasing the WinJS.Application Object The next line of code in the default.js file is used to alias the WinJS.Application object: var app = WinJS.Application; This line of code enables you to use a short-hand syntax when referring to the WinJS.Application object: for example,  app.onactivated instead of WinJS.Application.onactivated. The WinJS.Application object  represents your running Metro application. Handling Application Events The default.js file contains an event handler for the WinJS.Application activated event: app.onactivated = function (eventObject) { if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) { if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) { // TODO: This application has been newly launched. Initialize // your application here. } else { // TODO: This application has been reactivated from suspension. // Restore application state here. } WinJS.UI.processAll(); } }; This WinJS.Application class supports the following events: · loaded – Happens after browser DOMContentLoaded event. After this event, the DOM is ready and you can access elements in a page. This event is raised before external images have been loaded. · activated – Triggered by the Windows.UI.WebUI.WebUIApplication activated event. After this event, the WinRT is ready. · ready – Happens after both loaded and activated events. · unloaded – Happens before application is unloaded. The following default.js file has been modified to capture each of these events and write a message to the Visual Studio JavaScript Console window: (function () { "use strict"; var app = WinJS.Application; WinJS.Application.onloaded = function (e) { console.log("Loaded"); }; WinJS.Application.onactivated = function (e) { console.log("Activated"); }; WinJS.Application.onready = function (e) { console.log("Ready"); } WinJS.Application.onunload = function (e) { console.log("Unload"); } app.start(); })(); When you execute the code above, a message is written to the Visual Studio JavaScript Console window when each event occurs with the exception of the Unload event (presumably because the console is not attached when that event is raised).   Handling Different Activation Contexts The code for the activated handler in the default.js file looks like this: app.onactivated = function (eventObject) { if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) { if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) { // TODO: This application has been newly launched. Initialize // your application here. } else { // TODO: This application has been reactivated from suspension. // Restore application state here. } WinJS.UI.processAll(); } }; Notice that the code contains a conditional which checks the Kind of the event (the value of e.detail.kind). The startup code is executed only when the activated event is triggered by a Launch event, The ActivationKind enumeration has the following values: · launch · search · shareTarget · file · protocol · fileOpenPicker · fileSavePicker · cacheFileUpdater · contactPicker · device · printTaskSettings · cameraSettings Metro style applications can be activated in different contexts. For example, a camera application can be activated when modifying camera settings. In that case, the ActivationKind would be CameraSettings. Because we want to execute our JavaScript code when our application first launches, we verify that the kind of the activation event is an ActivationKind.Launch event. There is a second conditional within the activated event handler which checks whether an application is being newly launched or whether the application is being resumed from a suspended state. When running a Metro application with Visual Studio, you can use Visual Studio to simulate different application execution states by taking advantage of the Debug toolbar and the new Debug Location toolbar.  Handling the checkpoint Event The default.js file also includes an event handler for the WinJS.Application checkpoint event: app.oncheckpoint = function (eventObject) { // TODO: This application is about to be suspended. Save any state // that needs to persist across suspensions here. You might use the // WinJS.Application.sessionState object, which is automatically // saved and restored across suspension. If you need to complete an // asynchronous operation before your application is suspended, call // eventObject.setPromise(). }; The checkpoint event is raised when your Metro application goes into a suspended state. The idea is that you can save your application data when your application is suspended and reload your application data when your application resumes. Starting the Application The final statement in the default.js file is the statement that gets everything going: app.start(); Events are queued up in a JavaScript array named eventQueue . Until you call the start() method, the events in the queue are not processed. If you don’t call the start() method then the Loaded, Activated, Ready, and Unloaded events are never raised. Summary The goal of this blog entry was to describe the contents of the default.js file which is the JavaScript file which you use to kick off your custom code in a Windows Metro style application written with JavaScript. In this blog entry, I discussed the module pattern, JavaScript strict mode, handling first chance exceptions, WinJS Application events, and activation contexts.

    Read the article

  • Error in code of basic game using multiple sprites and surfaceView [on hold]

    - by Khagendra Nath Mahato
    I am a beginner to android and i was trying to make a basic game with the help of an online video tutorial. I am having problem with the multi-sprites and how to use with surfaceview.The application fails launching. Here is the code of the game.please help me. package com.example.killthemall; import java.util.ArrayList; import java.util.List; import java.util.Random; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Bundle; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.Toast; public class Game extends Activity { KhogenView View1; @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); while(true){ try { OurThread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }} } Thread OurThread; int herorows = 4; int herocolumns = 3; int xpos, ypos; int xspeed; int yspeed; int herowidth; int widthnumber = 0; int heroheight; Rect src; Rect dst; int round; Bitmap bmp1; // private Bitmap bmp1;//change name public List<Sprite> sprites = new ArrayList<Sprite>() { }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); View1 = new KhogenView(this); setContentView(View1); sprites.add(createSprite(R.drawable.image)); sprites.add(createSprite(R.drawable.bad1)); sprites.add(createSprite(R.drawable.bad2)); sprites.add(createSprite(R.drawable.bad3)); sprites.add(createSprite(R.drawable.bad4)); sprites.add(createSprite(R.drawable.bad5)); sprites.add(createSprite(R.drawable.bad6)); sprites.add(createSprite(R.drawable.good1)); sprites.add(createSprite(R.drawable.good2)); sprites.add(createSprite(R.drawable.good3)); sprites.add(createSprite(R.drawable.good4)); sprites.add(createSprite(R.drawable.good5)); sprites.add(createSprite(R.drawable.good6)); } private Sprite createSprite(int image) { // TODO Auto-generated method stub bmp1 = BitmapFactory.decodeResource(getResources(), image); return new Sprite(this, bmp1); } public class KhogenView extends SurfaceView implements Runnable { SurfaceHolder OurHolder; Canvas canvas = null; Random rnd = new Random(); { xpos = rnd.nextInt(canvas.getWidth() - herowidth)+herowidth; ypos = rnd.nextInt(canvas.getHeight() - heroheight)+heroheight; xspeed = rnd.nextInt(10 - 5) + 5; yspeed = rnd.nextInt(10 - 5) + 5; } public KhogenView(Context context) { super(context); // TODO Auto-generated constructor stub OurHolder = getHolder(); OurThread = new Thread(this); OurThread.start(); } @Override public void run() { // TODO Auto-generated method stub herowidth = bmp1.getWidth() / 3; heroheight = bmp1.getHeight() / 4; boolean isRunning = true; while (isRunning) { if (!OurHolder.getSurface().isValid()) continue; canvas = OurHolder.lockCanvas(); canvas.drawRGB(02, 02, 50); for (Sprite sprite : sprites) { if (widthnumber == 3) widthnumber = 0; update(); getdirection(); src = new Rect(widthnumber * herowidth, round * heroheight, (widthnumber + 1) * herowidth, (round + 1)* heroheight); dst = new Rect(xpos, ypos, xpos + herowidth, ypos+ heroheight); canvas.drawBitmap(bmp1, src, dst, null); } widthnumber++; OurHolder.unlockCanvasAndPost(canvas); } } public void update() { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (xpos + xspeed <= 0) xspeed = 40; if (xpos >= canvas.getWidth() - herowidth) xspeed = -50; if (ypos + yspeed <= 0) yspeed = 45; if (ypos >= canvas.getHeight() - heroheight) yspeed = -55; xpos = xpos + xspeed; ypos = ypos + yspeed; } public void getdirection() { double angleinteger = (Math.atan2(yspeed, xspeed)) / (Math.PI / 2); round = (int) (Math.round(angleinteger) + 2) % herorows; // Toast.makeText(this, String.valueOf(round), // Toast.LENGTH_LONG).show(); } } public class Sprite { Game game; private Bitmap bmp; public Sprite(Game game, Bitmap bmp) { // TODO Auto-generated constructor stub this.game = game; this.bmp = bmp; } } } Here is the LogCat if it helps.... 08-22 23:18:06.980: D/AndroidRuntime(28151): Shutting down VM 08-22 23:18:06.980: W/dalvikvm(28151): threadid=1: thread exiting with uncaught exception (group=0xb3f6f4f0) 08-22 23:18:06.980: D/AndroidRuntime(28151): procName from cmdline: com.example.killthemall 08-22 23:18:06.980: E/AndroidRuntime(28151): in writeCrashedAppName, pkgName :com.example.killthemall 08-22 23:18:06.980: D/AndroidRuntime(28151): file written successfully with content: com.example.killthemall StringBuffer : ;com.example.killthemall 08-22 23:18:06.990: I/Process(28151): Sending signal. PID: 28151 SIG: 9 08-22 23:18:06.990: E/AndroidRuntime(28151): FATAL EXCEPTION: main 08-22 23:18:06.990: E/AndroidRuntime(28151): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.killthemall/com.example.killthemall.Game}: java.lang.NullPointerException 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.os.Handler.dispatchMessage(Handler.java:99) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.os.Looper.loop(Looper.java:130) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.main(ActivityThread.java:3683) 08-22 23:18:06.990: E/AndroidRuntime(28151): at java.lang.reflect.Method.invokeNative(Native Method) 08-22 23:18:06.990: E/AndroidRuntime(28151): at java.lang.reflect.Method.invoke(Method.java:507) 08-22 23:18:06.990: E/AndroidRuntime(28151): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880) 08-22 23:18:06.990: E/AndroidRuntime(28151): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:638) 08-22 23:18:06.990: E/AndroidRuntime(28151): at dalvik.system.NativeStart.main(Native Method) 08-22 23:18:06.990: E/AndroidRuntime(28151): Caused by: java.lang.NullPointerException 08-22 23:18:06.990: E/AndroidRuntime(28151): at com.example.killthemall.Game$KhogenView.<init>(Game.java:96) 08-22 23:18:06.990: E/AndroidRuntime(28151): at com.example.killthemall.Game.onCreate(Game.java:58) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 08-22 23:18:06.990: E/AndroidRuntime(28151): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 08-22 23:18:06.990: E/AndroidRuntime(28151): ... 11 more 08-22 23:18:18.050: D/AndroidRuntime(28191): Shutting down VM 08-22 23:18:18.050: W/dalvikvm(28191): threadid=1: thread exiting with uncaught exception (group=0xb3f6f4f0) 08-22 23:18:18.050: I/Process(28191): Sending signal. PID: 28191 SIG: 9 08-22 23:18:18.050: D/AndroidRuntime(28191): procName from cmdline: com.example.killthemall 08-22 23:18:18.050: E/AndroidRuntime(28191): in writeCrashedAppName, pkgName :com.example.killthemall 08-22 23:18:18.050: D/AndroidRuntime(28191): file written successfully with content: com.example.killthemall StringBuffer : ;com.example.killthemall 08-22 23:18:18.050: E/AndroidRuntime(28191): FATAL EXCEPTION: main 08-22 23:18:18.050: E/AndroidRuntime(28191): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.killthemall/com.example.killthemall.Game}: java.lang.NullPointerException 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.os.Handler.dispatchMessage(Handler.java:99) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.os.Looper.loop(Looper.java:130) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.main(ActivityThread.java:3683) 08-22 23:18:18.050: E/AndroidRuntime(28191): at java.lang.reflect.Method.invokeNative(Native Method) 08-22 23:18:18.050: E/AndroidRuntime(28191): at java.lang.reflect.Method.invoke(Method.java:507) 08-22 23:18:18.050: E/AndroidRuntime(28191): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880) 08-22 23:18:18.050: E/AndroidRuntime(28191): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:638) 08-22 23:18:18.050: E/AndroidRuntime(28191): at dalvik.system.NativeStart.main(Native Method) 08-22 23:18:18.050: E/AndroidRuntime(28191): Caused by: java.lang.NullPointerException 08-22 23:18:18.050: E/AndroidRuntime(28191): at com.example.killthemall.Game$KhogenView.<init>(Game.java:96) 08-22 23:18:18.050: E/AndroidRuntime(28191): at com.example.killthemall.Game.onCreate(Game.java:58) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049) 08-22 23:18:18.050: E/AndroidRuntime(28191): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 08-22 23:18:18.050: E/AndroidRuntime(28191): ... 11 more

    Read the article

  • Unexpected StackOverflowError in KeyListener

    - by BillThePlatypus
    I am writing a program that can write sets of questions for review to a file for another program to read. The possible answers are typed into JTextFields at the bottom. It has code to ensure that there won't bew more than one blank JTextField at the end. When I type in answers, at varying points it will throw a StackOverflowError. The stack trace: Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) and the code: package writer; import java.awt.BorderLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import main.QuestionSet; public class SetPanel extends JPanel implements KeyListener { private QuestionSet set; private WriterPanel writer; private JPanel top=new JPanel(new BorderLayout()),controls=new JPanel(new GridLayout(1,0)),answerPanel=new JPanel(new GridLayout(0,1)); private JSplitPane split; private JTextField title=new JTextField(); private JTextArea question=new JTextArea(); private ArrayList<JTextField> answers=new ArrayList<JTextField>(); public SetPanel(QuestionSet s,WriterPanel writer) { super(new BorderLayout()); top.add(controls,BorderLayout.PAGE_START); title.setFont(title.getFont().deriveFont(40f)); title.addKeyListener(new KeyListener(){ @Override public void keyTyped(KeyEvent e) { title.setText(WriterPanel.convertString(title.getText())); } @Override public void keyPressed(KeyEvent e) { title.setText(WriterPanel.convertString(title.getText())); } @Override public void keyReleased(KeyEvent e) { title.setText(WriterPanel.convertString(title.getText())); } }); title.getDocument().addDocumentListener(new DocumentListener(){ @Override public void insertUpdate(DocumentEvent e) { // TODO Auto-generated method stub fitTitle(); } @Override public void removeUpdate(DocumentEvent e) { // TODO Auto-generated method stub fitTitle(); } @Override public void changedUpdate(DocumentEvent e) { // TODO Auto-generated method stub fitTitle(); } }); top.add(title,BorderLayout.PAGE_END); this.add(top,BorderLayout.PAGE_START); question.setLineWrap(true); question.setWrapStyleWord(true); question.setFont(question.getFont().deriveFont(20f)); question.addKeyListener(new KeyListener(){ @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub question.setText(WriterPanel.convertString(question.getText())); } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub question.setText(WriterPanel.convertString(question.getText())); } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub question.setText(WriterPanel.convertString(question.getText())); }}); split=new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,new JScrollPane(question),new JScrollPane(answerPanel)); split.setDividerLocation(150); this.add(split,BorderLayout.CENTER); answers.add(new JTextField()); answerPanel.add(answers.get(0)); answers.get(0).addKeyListener(this); } private void fitTitle() { if(title==null||title.getText().equals("")) return; //title.setText(WriterPanel.convertString(title.getText())); String text=title.getText(); Insets insets=title.getInsets(); int width=title.getWidth()-insets.left-insets.right; int height=title.getHeight()-insets.top-insets.bottom; Font root=title.getFont().deriveFont((float)height); FontMetrics m=title.getFontMetrics(root); if(m.stringWidth(text)<width) { title.setFont(title.getFont().deriveFont((float)height)); return; } float delta=-100; while(Math.abs(delta)>.1f) { m=title.getFontMetrics(root); int w=m.stringWidth(text); if(w==width) break; if(Math.signum(w-width)==Math.signum(delta)||root.getSize2D()+delta<0) { delta/=-10; continue; } root=root.deriveFont(root.getSize2D()+delta); } title.setFont(root); } private void fixAnswers() { //System.out.println(answers); while(answers.get(answers.size()-1).getText().equals("")&&answers.size()>1&&answers.get(answers.size()-2).getText().equals("")) removeAnswer(answers.size()-1); if(!answers.get(answers.size()-1).getText().equals("")) { answers.add(new JTextField()); answerPanel.add(answers.get(answers.size()-1)); answers.get(answers.size()-2).removeKeyListener(this); answerPanel.revalidate(); } answers.get(answers.size()-1).addKeyListener(this); } private void removeAnswer(int i) { answers.remove(i); answerPanel.remove(i); answerPanel.revalidate(); } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub fixAnswers(); } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } } Thank you in advance for any help.

    Read the article

  • NetworkOnMainThreadException while using AsyncTask

    - by Fansher
    Im making an app that uses the internet to retrive information. I get an NetworkOnMainThreadException as i tried to run it on 3.0 and above and have therefore tried to set it up using AsyncTask, but it still gives the exception and i don't know what is wrong. Oddly enough i read on this thread Android NetworkOnMainThreadException inside of AsyncTask that if you just removes the android:targetSdkVersion="10" statement from the manifest file it will be able to run. This works but i don't find it as the right solution to solve the problem this way. So if anyone can tell me what im doing wrong with the AsyncTask i will really appriciate it. Also if there is anybody that knows why removing the statement in the manifest makes it work, im really interested in that also. My code looks like this: public class MainActivity extends Activity { static ArrayList<Tumblr> tumblrs; ListView listView; TextView footer; int offset = 0; ProgressDialog pDialog; View v; String responseBody = null; HttpResponse r; HttpEntity e; String searchUrl; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo(); if (activeNetwork != null && activeNetwork.isConnected()) { setContentView(R.layout.main); try { tumblrs = getTumblrs(); listView = (ListView) findViewById(R.id.list); View v = getLayoutInflater().inflate(R.layout.footer_layout, null); footer = (TextView) v.findViewById(R.id.tvFoot); listView.addFooterView(v); listView.setAdapter(new UserItemAdapter(this, R.layout.listitem)); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } new GetChicks().execute(); footer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new loadMoreListView().execute(); } }); } else { setContentView(R.layout.nonet); } } public class UserItemAdapter extends ArrayAdapter<Tumblr> { public UserItemAdapter(Context context, int imageViewResourceId) { super(context, imageViewResourceId, tumblrs); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.listitem, null); } Tumblr tumblr = tumblrs.get(position); if (tumblr != null) { ImageView image = (ImageView) v.findViewById(R.id.avatar); if (image != null) { image.setImageBitmap(getBitmap(tumblr.image_url)); } } return v; } } public Bitmap getBitmap(String bitmapUrl) { try { URL url = new URL(bitmapUrl); return BitmapFactory.decodeStream(url.openConnection() .getInputStream()); } catch (Exception ex) { return null; } } public ArrayList<Tumblr> getTumblrs() throws ClientProtocolException, IOException, JSONException { searchUrl = "http://api.tumblr.com/v2/blog/"webside"/posts?api_key=API_KEY"; ArrayList<Tumblr> tumblrs = new ArrayList<Tumblr>(); return tumblrs; } private class GetChicks extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... unused) { // TODO Auto-generated method stub runOnUiThread(new Runnable() { public void run() { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(searchUrl); HttpResponse r = null; try { r = client.execute(get); int status = r.getStatusLine().getStatusCode(); if (status == 200) { e = r.getEntity(); responseBody = EntityUtils.toString(e); } } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JSONObject jsonObject; try { jsonObject = new JSONObject(responseBody); JSONArray posts = jsonObject.getJSONObject("response") .getJSONArray("posts"); for (int i = 0; i < posts.length(); i++) { JSONArray photos = posts.getJSONObject(i) .getJSONArray("photos"); for (int j = 0; j < photos.length(); j++) { JSONObject photo = photos.getJSONObject(j); String url = photo.getJSONArray("alt_sizes") .getJSONObject(0).getString("url"); Tumblr tumblr = new Tumblr(url); tumblrs.add(tumblr); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); return null; } } public class Tumblr { public String image_url; public Tumblr(String url) { this.image_url = url; } } private class loadMoreListView extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { // Showing progress dialog before sending http request pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("More chicks coming up.."); pDialog.setIndeterminate(true); pDialog.setCancelable(false); pDialog.show(); } @Override protected Void doInBackground(Void... unused) { // TODO Auto-generated method stub runOnUiThread(new Runnable() { public void run() { // increment current page offset += 2; // Next page request tumblrs.clear(); String searchUrl = "http://api.tumblr.com/v2/blog/"webside"/posts?api_key=API_KEY&limit=2 + offset; HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(searchUrl); HttpResponse r = null; try { r = client.execute(get); int status = r.getStatusLine().getStatusCode(); if (status == 200) { HttpEntity e = r.getEntity(); responseBody = EntityUtils.toString(e); } } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JSONObject jsonObject; try { jsonObject = new JSONObject(responseBody); JSONArray posts = jsonObject.getJSONObject("response") .getJSONArray("posts"); for (int i = 0; i < posts.length(); i++) { JSONArray photos = posts.getJSONObject(i) .getJSONArray("photos"); for (int j = 0; j < photos.length(); j++) { JSONObject photo = photos.getJSONObject(j); String url = photo.getJSONArray("alt_sizes") .getJSONObject(0).getString("url"); Tumblr tumblr = new Tumblr(url); tumblrs.add(tumblr); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Setting new scroll position listView.setSelectionFromTop(0, 0); } }); return null; } protected void onPostExecute(Void unused) { pDialog.dismiss(); } } @Override public boolean onCreateOptionsMenu(android.view.Menu menu) { // TODO Auto-generated method stub super.onCreateOptionsMenu(menu); MenuInflater blowUp = getMenuInflater(); blowUp.inflate(R.menu.cool_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case R.id.aboutUs: Intent i = new Intent("com.example.example.ABOUT"); startActivity(i); break; case R.id.refresh: Intent f = new Intent(MainActivity.this, MainActivity.class); startActivity(f); finish(); break; case R.id.exit: finish(); break; } return false; } } Thanks for helping out.

    Read the article

  • How to maintain the state of button cutom listview in android

    - by Akshay
    I have custom ListView with three TextView three Button and three Chronometer. And the situation is I am loading the ListView properly.But while loading ListView I am disabling some button in the ListView by checking one parameter. Up to this point ListView is showing it's row properly. But when I am scrolling the ListView at that time previously enabled Button are getting disabled.What I am doing wrong I am not getting can one please point out my mistake Or any suggestion. Here is my Adapter class. public class OrderSmartKitchenAdapter extends BaseAdapter { private int flagDeliveryComplete = 0; private int flagPreparationComplete = 0; private int flagPreparationStarted = 0; private List<OrderitemdetailsBO> list = new ArrayList<OrderitemdetailsBO(); private int orderStatus; public OrderSmartKitchenAdapter() { // TODO Auto-generated constructor stub } public void setOrderList(List<OrderitemdetailsBO> orderList) { this.list = orderList; } @Override public int getCount() { // TODO Auto-generated method stub Log.i("OrderItemList Size :-", Integer.toString(list.size())); return list.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(final int position, View convertView,ViewGroup parent) { // TODO Auto-generated method stub final ViewHolder viewHolder ; if (convertView == null) { layoutInflater = LayoutInflater.from(myContext); convertView = layoutInflater.inflate(R.layout.table_row_view,null); viewHolder = new ViewHolder(); viewHolder.txtTableNumber = (TextView) convertView.findViewById(R.id.txtTableNumber); viewHolder.txtMenuItem = (TextView) convertView.findViewById(R.id.txtMenuItem); viewHolder.txtQuantity = (TextView) convertView.findViewById(R.id.txtQuantity); viewHolder.txtOrderAcceptanceTime = (TextView) convertView.findViewById(R.id.txtOrderAcceptanceTime); viewHolder.txtElapsedTimeOfOrderAcceptance = (Chronometer) convertView.findViewById(R.id.txtElapsedTimeOfOrderAcceptance); viewHolder.btnPreparationStart = (Button) convertView.findViewById(R.id.btnPreparationStart); viewHolder.btnPreparationStart.setTag(position); viewHolder.txtElapsedTimeForPreparation = (Chronometer) convertView.findViewById(R.id.txtElapsedTimeForPrepatration); viewHolder.btnPreparationComplete = (Button) convertView.findViewById(R.id.btnPreparationCompleted); viewHolder.btnPreparationComplete.setTag(position); viewHolder.txtElapsedTimeForDeliveryComplete = (Chronometer) convertView.findViewById(R.id.txtElapsedTimeForCompleation); viewHolder.btnDeliveryComplete = (Button) convertView.findViewById(R.id.btnOrderComplete); viewHolder.btnDeliveryComplete.setTag(position); convertView.setTag(viewHolder); } else{ viewHolder = (ViewHolder)convertView.getTag(); viewHolder.btnDeliveryComplete.setTag(position); viewHolder.btnPreparationComplete.setTag(position); viewHolder.btnPreparationStart.setTag(position); } if (list.get(position) != null) { OrderitemdetailsBO orderitemdetailsBO = new OrderitemdetailsBO(); orderitemdetailsBO = list.get(position); viewHolder.txtTableNumber.setText(orderitemdetailsBO.getOrderitemid().toString()); viewHolder.txtMenuItem.setText(orderitemdetailsBO.getMenuitemname().toString()); viewHolder.txtQuantity.setText(orderitemdetailsBO.getQuantity().toString()); Log.i("Table Number :-", Long.toString(orderitemdetailsBO.getOrderitemid())); Log.i("Menu Name :-", orderitemdetailsBO.getMenuitemname().toString()); Log.i("Quantity", orderitemdetailsBO.getQuantity().toString()); Date acceptTime = new Date(); acceptTime = orderitemdetailsBO.getOrderdatetime(); viewHolder.txtOrderAcceptanceTime.setText(DateUtil.getDateAsString(acceptTime,"HH:mm")); Log.i("Order Accept Time :-", acceptTime.getMinutes() + ":"+ acceptTime.getSeconds()); orderStatus = orderitemdetailsBO.getOrderstatus(); Date preparationStartTime = new Date(); preparationStartTime = orderitemdetailsBO.getPreparationstarttime(); if(preparationStartTime != null) { Log.i("OrderSmartKitchenActivity", "2 Order Acceptance Time :-" + "Menu Item id "+ orderitemdetailsBO.getOrderitemid() + " Preparation Start time " + orderitemdetailsBO.getPreparationstarttime() ); viewHolder.txtElapsedTimeOfOrderAcceptance.stop(); Log.i("Preparation Start Time :-",preparationStartTime.getMinutes() + ":" + preparationStartTime.getSeconds()); viewHolder.txtElapsedTimeOfOrderAcceptance.setText(DateUtil.getDateAsString(preparationStartTime,"MM:ss")); viewHolder.txtElapsedTimeOfOrderAcceptance.stop(); viewHolder.btnPreparationStart.setEnabled(false); viewHolder.btnPreparationStart.setClickable(false); viewHolder.btnPreparationStart.setBackgroundColor(Color.LTGRAY); } else { Long n = acceptTime.getTime(); Log.i("OrderSmartKitchenActivity", "Order Acceptance Time :-" + "Menu Item id "+ orderitemdetailsBO.getOrderitemid() + " Acceptance time" + Long.toString(n) + " Preparation Start time " + orderitemdetailsBO.getPreparationstarttime() ); // Calculate Time difference viewHolder.txtElapsedTimeOfOrderAcceptance.setBase(SystemClock.elapsedRealtime() - System.currentTimeMillis() + n); viewHolder.txtElapsedTimeOfOrderAcceptance.getBase(); viewHolder.txtElapsedTimeOfOrderAcceptance.start(); viewHolder.txtElapsedTimeOfOrderAcceptance.setFormat("%s"); } viewHolder.btnPreparationStart.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { // TODO Auto-generated method stub if (flagPreparationStarted == 0) { flagPreparationStarted++; v.startAnimation(playAnimation()); handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub v.clearAnimation(); Date currentTime = new Date(); // Set Preparation Start Time. viewHolder.txtElapsedTimeOfOrderAcceptance.stop(); Date setTime = new Date(currentTime.getTime() * 1000); OrderitemdetailsBO orderitemdetailsBO = list.get(position); orderitemdetailsBO.setPreparationstarttime(setTime); String orderDetails = "2"; String getPosition = Integer.toString(position); viewHolder.btnPreparationStart.setBackgroundColor(Color.LTGRAY); new sendOrderStatusToServer().execute(orderDetails,getPosition); } }, 5000); } else { handler.removeCallbacksAndMessages(null); v.clearAnimation(); flagPreparationStarted = 0; Log.i("Handler Removed. :-", "Here"); } } }); String preparationTime = orderitemdetailsBO.getOrderpreparationtime(); if(preparationTime != null && orderStatus == order_preparationComplete) { viewHolder.txtElapsedTimeForPreparation.setText(preparationTime); viewHolder.txtElapsedTimeForPreparation.stop(); viewHolder.btnPreparationComplete.getTag(position); viewHolder.btnPreparationComplete.setEnabled(false); viewHolder.btnPreparationComplete.setClickable(false); viewHolder.btnPreparationComplete.setBackgroundColor(Color.LTGRAY); } else if( orderStatus == order_preparationStart || orderStatus == orderReceived || orderStatus == order_delivered){ Long n = acceptTime.getTime(); Log.i("Preparation Start Time :-", Long.toString(n)); viewHolder.txtElapsedTimeForPreparation.setBase(SystemClock.elapsedRealtime() - System.currentTimeMillis() + n); viewHolder.txtElapsedTimeForPreparation.getBase(); viewHolder.txtElapsedTimeForPreparation.start(); viewHolder.txtElapsedTimeForPreparation.setFormat("%s"); } viewHolder.btnPreparationComplete.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { // TODO Auto-generated method if (flagPreparationComplete == 0) { flagPreparationComplete++; v.startAnimation(playAnimation()); handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub v.clearAnimation(); OrderitemdetailsBO orderitemdetailsBO = list.get(position); Date date = orderitemdetailsBO.getPreparationstarttime(); if(date != null) { viewHolder.txtElapsedTimeForPreparation.stop(); Date currentTime = new Date(); Calendar calendar = Calendar.getInstance(); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); orderitemdetailsBO.setOrderpreparationtime(calendar.get(Calendar.MINUTE) +":" +calendar.get(Calendar.SECOND)); String orderDetails = "3"; String getPosition = Integer.toString(position); viewHolder.btnPreparationComplete.setBackgroundColor(Color.LTGRAY); new sendOrderStatusToServer().execute(orderDetails,getPosition); } else { Toast.makeText(myContext, "Please Enter Preparation Start Time.", Toast.LENGTH_LONG).show(); } } }, 5000); } else { handler.removeCallbacksAndMessages(null); v.clearAnimation(); flagPreparationComplete = 0; } } }); String deleveredTime = orderitemdetailsBO.getOrderdeliverytime(); if(deleveredTime != null && orderStatus == order_delivered) { Date delevered = new Date(Long.parseLong(deleveredTime)); viewHolder.txtElapsedTimeForPreparation.setText(DateUtil.getDateAsString(delevered,"MM:ss")); Log.i("Preparation Start Time :-", delevered.getMinutes()+":"+delevered.getSeconds()); viewHolder.txtElapsedTimeForPreparation.stop(); viewHolder.btnDeliveryComplete.getTag(position); viewHolder.btnDeliveryComplete.setEnabled(false); viewHolder.btnDeliveryComplete.setClickable(false); viewHolder.btnDeliveryComplete.setBackgroundColor(Color.LTGRAY); } else if(orderStatus == 3 || orderStatus == 2 || orderStatus == 1) { Long n = acceptTime.getTime(); Log.i("Preparation Start Time :-", Long.toString(n)); viewHolder.txtElapsedTimeForDeliveryComplete.setTag(list.get(position)); viewHolder.txtElapsedTimeForDeliveryComplete.setBase(SystemClock.elapsedRealtime() - System.currentTimeMillis() + n); viewHolder.txtElapsedTimeForDeliveryComplete.getBase(); viewHolder.txtElapsedTimeForDeliveryComplete.start(); viewHolder.txtElapsedTimeForDeliveryComplete.setFormat("%s"); } viewHolder.btnDeliveryComplete.setOnClickListener(new OnClickListener() { @Override public void onClick(final View v) { // TODO Auto-generated method stub if (flagDeliveryComplete == 0) { flagDeliveryComplete++; v.startAnimation(playAnimation()); handler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub v.clearAnimation(); OrderitemdetailsBO orderitemdetailsBO = list.get(position); Date date = orderitemdetailsBO.getPreparationstarttime(); String preparationComplete = orderitemdetailsBO.getOrderpreparationtime(); if(date != null && preparationComplete != null ) { Date currentTime = new Date(); Calendar calendar = Calendar.getInstance(); viewHolder.txtElapsedTimeForDeliveryComplete.stop(); orderitemdetailsBO.setOrderdeliverytime(calendar.get(Calendar.MINUTE) +":"+calendar.get(Calendar.SECOND)); String orderDetails = Integer.toString(order_delivered); String getPosition = Integer.toString(position); viewHolder.btnDeliveryComplete.setBackgroundColor(Color.LTGRAY); new sendOrderStatusToServer().execute(orderDetails,getPosition); } else { Toast.makeText(myContext, "Please Enter Preparation Start Time & Preparation Complete Time.", Toast.LENGTH_LONG).show(); } } }, 5000); } else { handler.removeCallbacksAndMessages(null); v.clearAnimation(); flagDeliveryComplete = 0; } } }); } return convertView; } } private static class ViewHolder { protected TextView txtTableNumber; protected TextView txtMenuItem; protected TextView txtQuantity; protected TextView txtOrderAcceptanceTime; protected Chronometer txtElapsedTimeOfOrderAcceptance; protected Button btnPreparationStart; protected Chronometer txtElapsedTimeForPreparation; protected Button btnPreparationComplete; protected Chronometer txtElapsedTimeForDeliveryComplete; protected Button btnDeliveryComplete; }

    Read the article

  • Multiple overlay items in android

    - by Bostjan
    I seem to be having a problem with using ItemizedOverlay and OveralyItems in it. I can get the first overlayItem to appear on the map but not any items after that. Code sample is on: http://www.anddev.org/multiple_overlay_items-t12171.html Quick overview here: public class Markers extends ItemizedOverlay { private Context ctx; private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>(); public Markers(Drawable defaultMarker, Context cont) { super(boundCenterBottom(defaultMarker)); this.ctx = cont; // TODO Auto-generated constructor stub } @Override protected OverlayItem createItem(int i) { // TODO Auto-generated method stub return mOverlays.get(i); } @Override public boolean onTap(GeoPoint p, MapView mapView) { // TODO Auto-generated method stub return super.onTap(p, mapView); } @Override protected boolean onTap(int index) { // TODO Auto-generated method stub Toast.makeText(this.ctx, mOverlays.get(index).getTitle().toString()+", Latitude: "+mOverlays.get(index).getPoint().getLatitudeE6(), Toast.LENGTH_SHORT).show(); return super.onTap(index); } @Override public int size() { // TODO Auto-generated method stub return mOverlays.size(); } public void addOverlay(OverlayItem item) { mOverlays.add(item); setLastFocusedIndex(-1); populate(); } public void clear() { mOverlays.clear(); setLastFocusedIndex(-1); populate(); }} Markers usersMarker = new Markers(user,overview.this); GeoPoint p = new GeoPoint((int) (lat * 1E6),(int) (lon * 1E6)); OverlayItem item = new OverlayItem(p,userData[0],userData[3]); item.setMarker(this.user); usersMarker.addOverlay(item); The lines after the class are just samples of how it's used the first marker shows up on the map but if I add any more they don't show up? Is there a problem with the populate() method? I tried calling it manually after adding all markers but it still didn't help. Please, if you have any idea what could be wrong, say so.

    Read the article

  • Zend Framework: How to start PHPUnit testing Forms?

    - by Andrew
    I am having trouble getting my filters/validators to work correctly on my form, so I want to create a Unit test to verify that the data I am submitting to my form is being filtered and validated correctly. I started by auto-generating a PHPUnit test in Zend Studio, which gives me this: <?php require_once 'PHPUnit/Framework/TestCase.php'; /** * Form_Event test case. */ class Form_EventTest extends PHPUnit_Framework_TestCase { /** * @var Form_Event */ private $Form_Event; /** * Prepares the environment before running a test. */ protected function setUp () { parent::setUp(); // TODO Auto-generated Form_EventTest::setUp() $this->Form_Event = new Form_Event(/* parameters */); } /** * Cleans up the environment after running a test. */ protected function tearDown () { // TODO Auto-generated Form_EventTest::tearDown() $this->Form_Event = null; parent::tearDown(); } /** * Constructs the test case. */ public function __construct () { // TODO Auto-generated constructor } /** * Tests Form_Event->init() */ public function testInit () { // TODO Auto-generated Form_EventTest->testInit() $this->markTestIncomplete( "init test not implemented"); $this->Form_Event->init(/* parameters */); } /** * Tests Form_Event->getFormattedMessages() */ public function testGetFormattedMessages () { // TODO Auto-generated Form_EventTest->testGetFormattedMessages() $this->markTestIncomplete( "getFormattedMessages test not implemented"); $this->Form_Event->getFormattedMessages(/* parameters */); } } so then I open up terminal, navigate to the directory, and try to run the test: $ cd my_app/tests/unit/application/forms $ phpunit EventTest.php Fatal error: Class 'Form_Event' not found in .../tests/unit/application/forms/EventTest.php on line 19 So then I add a require_once at the top to include my Form class and try it again. Now it says it can't find another class. I include that one and try it again. Then it says it can't find another class, and another class, and so on. I have all of these dependencies on all these other Zend_Form classes. What should I do? How should I go about testing my Form to make sure my Validators and Filters are being attached correctly, and that it's doing what I expect it to do. Or am I thinking about this the wrong way?

    Read the article

  • ViewPager cycle between views?

    - by Erdem Azakli
    I want my ViewPager implementation to cycle between views instead of stopping at the last view. For example, if I have 3 views to display via a ViewPager, it should return back to the first View after the third View on fling instead of stopping at that third view. I want it to return to the first page/view when the user flings forward on the last page Thanks, Mypageradapter; package com.example.pictures; import android.content.Context; import android.media.AudioManager; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; public class MyPagerAdapter extends PagerAdapter{ SoundManager snd; int sound1,sound2,sound3; boolean loaded = false; public int getCount() { return 6; } public Object instantiateItem(View collection, int position) { View view=null; LayoutInflater inflater = (LayoutInflater) collection.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.setVolumeControlStream(AudioManager.STREAM_MUSIC); int resId = 0; switch (position) { case 0: resId = R.layout.picture1; view = inflater.inflate(resId, null); break; case 1: resId = R.layout.picture2; view = inflater.inflate(resId, null); break; case 2: resId = R.layout.picture3; view = inflater.inflate(resId, null); break; case 3: resId = R.layout.picture4; view = inflater.inflate(resId, null); break; case 4: resId = R.layout.picture5; view = inflater.inflate(resId, null); break; case 5: resId = R.layout.picture6; view = inflater.inflate(resId, null); break; } ((ViewPager) collection).addView(view, 0); return view; } @SuppressWarnings("unused") private Context getApplicationContext() { // TODO Auto-generated method stub return null; } private void setVolumeControlStream(int streamMusic) { // TODO Auto-generated method stub } @SuppressWarnings("unused") private Context getBaseContext() { // TODO Auto-generated method stub return null; } @SuppressWarnings("unused") private PagerAdapter findViewById(int myfivepanelpager) { // TODO Auto-generated method stub return null; } @Override public void destroyItem(View arg0, int arg1, Object arg2) { ((ViewPager) arg0).removeView((View) arg2); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == ((View) arg1); } @Override public Parcelable saveState() { return null; } public static Integer getItem(int position) { // TODO Auto-generated method stub return null; } } OnPageChangeListener; package com.example.pictures; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.widget.Button; import android.widget.Toast; public class Pictures extends Activity implements OnPageChangeListener{ SoundManager snd; int sound1,sound2,sound3; View view=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.picturespage); MyPagerAdapter adapter = new MyPagerAdapter(); ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager); myPager.setAdapter(adapter); myPager.setCurrentItem(0); myPager.setOnPageChangeListener(this); snd = new SoundManager(this); sound1 = snd.load(R.raw.sound1); sound2 = snd.load(R.raw.sound2); sound3 = snd.load(R.raw.sound3); } public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub } public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } public void onPageSelected(int position) { // TODO Auto-generated method stub switch (position) { case 0: snd.play(sound1); break; case 1: snd.play(sound2); break; case 2: snd.play(sound3); break; case 3: Toast.makeText(this, "1", Toast.LENGTH_SHORT).show(); break; case 4: Toast.makeText(this, "2", Toast.LENGTH_SHORT).show(); break; case 5: Toast.makeText(this, "3", Toast.LENGTH_SHORT).show(); break; } } };

    Read the article

  • How can I scrape the current webpage with php/javascript?

    - by Robert
    I have made the following webpage for generating interactive todo lists: http://robert-kent.com/todo/todo.php Basically, the user pastes a numbered todo list and each task is placed into it's own div with a unique id. Users can add notes to the tasks (done with javascript) and can click the green check when the task is done to hide it. I'd like to add an Export button which would generate a report of which tasks were completed and which were not, along with the user-entered notes. After a bit of searching I understand that what I want to do is scrape the page, but I haven't the faintest idea of the best way to do it. Many of the articles and tutorials I have found with Google involve scraping other sites and don't really explain how I could iterate over each div on the page. Full source here: http://pastebin.com/r7V3P5jK Any suggestions?

    Read the article

  • Unable to call RESTful web services methods

    - by Alessandro
    Hello, I'm trying to dive into the RESTful web services world and have started with the following template: [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class Test { // TODO: Implement the collection resource that will contain the SampleItem instances [WebGet(UriTemplate = ""), OperationContract] public List<SampleItem> GetCollection() { // TODO: Replace the current implementation to return a collection of SampleItem instances return new List<SampleItem>() {new SampleItem() {Id = 1, StringValue = "Hello"}}; } [WebInvoke(UriTemplate = "", Method = "POST"), OperationContract] public SampleItem Create(SampleItem instance) { // TODO: Add the new instance of SampleItem to the collection throw new NotImplementedException(); } [WebGet(UriTemplate = "{id}"), OperationContract] public SampleItem Get(string id) { // TODO: Return the instance of SampleItem with the given id throw new NotImplementedException(); } [WebInvoke(UriTemplate = "{id}", Method = "PUT"), OperationContract] public SampleItem Update(string id, SampleItem instance) { return new SampleItem { Id = 99, StringValue = "Done" }; } [WebInvoke(UriTemplate = "{id}", Method = "DELETE"), OperationContract] public void Delete(string id) { // TODO: Remove the instance of SampleItem with the given id from the collection throw new NotImplementedException(); } } I am able to perform the GET operation but I am unable to perform PUT, POST or DELETE requests. Can anyone explain me how to perform these operations and how to create the correct URLs? Best regards Alessandro

    Read the article

  • Assistance using respond_to to find the right actions to render PDF in ruby on rails

    - by Angela
    Hi, I am trying out Prince with the Princely plugin, which is supposed to format templates that have the .pdf into a PDF generator. Here is my controller: class TodoController < ApplicationController def show_date @date = Date.today @campaigns = Campaign.all @contacts = Contact.all @contacts.each do |contact| end respond_to do |format| format.html format.pdf do render :pdf => "filename", :stylesheets => ["application", "prince"], :layout => "pdf" end end end end I changed the routes.db to include the following: map.connect ':controller/:action.:format' map.todo "todo/today", :controller => "todo", :action => "show_date" My expected behavior is when I enter todo/today.pdf, it tries to execute show_date, but renders according to the princely plugin. Right now, it says cannot find action. What do I need to do to fix this?

    Read the article

  • PHP sessions and class members.

    - by JDW
    Ok, messing about with classes in PHP and can't get it to work the way I'm used to as a C++/Java-guy. In the "_init" funtion, if I run a query at the "// query works here" line", everythong works, but in the "getUserID" function, all that happens is said warning... "getUserID" gets called from login.php (they are in the same dir): login.php <?php include_once 'sitehandler.php'; include_once 'dbhandler.php'; session_start(); #TODO: Safer input handling $t_userName = $_POST["name"]; $t_userId = $_SESSION['handler']['db']->getUserID($t_userName); if ($t_userId != -1) { $_SESSION['user']['name'] = $t_userName; $_SESSION['user']['id'] = $t_userId; } //error_log("user: " . $_SESSION['user']['name'] . ", id: ". $_SESSION['user']['id']); header("Location: " . $_SERVER["HTTP_REFERER"]); ? dbhandler.php <?php include_once 'handler.php'; class DBHandler extends HandlerAbstract { private $m_handle; function __construct() { parent::__construct(); } public function test() { #TODO: isdir liquibase #TODO: isfile liquibase-195/liquibase + .bat + execrights $this->m_isTested = true; } public function _init() { if (!$this->isTested()) $this->test(); if (!file_exists('files/data.db')) { #TODO: How to to if host is Windows based? exec('./files/liquibase-1.9.5/liquibase --driver=org.sqlite.JDBC --changeLogFile=files/data_db.xml --url=jdbc:sqlite:files/data.db update'); #TODO: quit if not success } #TODO: Set with default data try { $this->m_handle = new SQLite3('files/data.db'); } catch (Exception $e) { die("<hr />" . $e->getMessage() . "<hr />"); } // query works here $this->m_isSetup = true; } public function teardown() { } public function getUserID($name) { // PHP Warning: SQLite3::prepare(): The SQLite3 object has not been correctly initialised in $t_statement = $this->m_handle->prepare("SELECT id FROM users WHERE name = :name"); $t_statement->bindValue(":name", $name, SQLITE3_TEXT); $t_result = $t_statement->execute(); //var_dump($this->m_handle); return ($t_result)? (int)$t_result['id']: -1; } }

    Read the article

  • Android: How/where to put gesture code into IME?

    - by CardinalFIB
    Hi, I'm new to Android but I'm trying to create an IME that allows for gesture-character recognition. I can already do simple apps that perform gesture recognition but am not sure where to hook in the gesture views/obj with an IME. Here is a starting skeleton of what I have for the IME so far. I would like to use android.gesture.Gesture/Prediction/GestureOverlayView/OnGesturePerformedListener. Does anyone have advice? -- CardinalFIB gestureIME.java public class gestureIME extends InputMethodService { private static Keyboard keyboard; private static KeyboardView kView; private int lastDisplayWidth; @Override public void onCreate() { super.onCreate(); } @Override public void onInitializeInterface() { int displayWidth; if (keyboard != null) { displayWidth = getMaxWidth(); if (displayWidth == lastDisplayWidth) return; else lastDisplayWidth = getMaxWidth(); } keyboard = new GestureKeyboard(this, R.xml.keyboard); } @Override public View onCreateInputView() { kView = (KeyboardView) getLayoutInflater().inflate(R.layout.input, null); kView.setOnKeyboardActionListener(kListener); kView.setKeyboard(keyboard); return kView; } @Override public View onCreateCandidatesView() { return null; } @Override public void onStartInputView(EditorInfo attribute, boolean restarting) { super.onStartInputView(attribute, restarting); kView.setKeyboard(keyboard); kView.closing(); //what does this do??? } @Override public void onStartInput(EditorInfo attribute, boolean restarting) { super.onStartInput(attribute, restarting); } @Override public void onFinishInput() { super.onFinishInput(); } public KeyboardView.OnKeyboardActionListener kListener = new KeyboardView.OnKeyboardActionListener() { @Override public void onKey(int keyCode, int[] otherKeyCodes) { if(keyCode==Keyboard.KEYCODE_CANCEL) handleClose(); if(keyCode==10) getCurrentInputConnection().commitText(String.valueOf((char) keyCode), 1); //keyCode RETURN } @Override public void onPress(int primaryCode) {} // TODO Auto-generated method stub @Override public void onRelease(int primaryCode) {} // TODO Auto-generated method stub @Override public void onText(CharSequence text) {} // TODO Auto-generated method stub @Override public void swipeDown() {} // TODO Auto-generated method stub @Override public void swipeLeft() {} // TODO Auto-generated method stub @Override public void swipeRight() {} // TODO Auto-generated method stub @Override public void swipeUp() {} // TODO Auto-generated method stub }; private void handleClose() { requestHideSelf(0); kView.closing(); } } GestureKeyboard.java package com.android.jt.gestureIME; import android.content.Context; import android.inputmethodservice.Keyboard; public class GestureKeyboard extends Keyboard { public GestureKeyboard(Context context, int xmlLayoutResId) { super(context, xmlLayoutResId); } } GesureKeyboardView.java package com.android.jt.gestureIME; import android.content.Context; import android.inputmethodservice.KeyboardView; import android.inputmethodservice.Keyboard.Key; import android.util.AttributeSet; public class GestureKeyboardView extends KeyboardView { public GestureKeyboardView(Context context, AttributeSet attrs) { super(context, attrs); } public GestureKeyboardView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected boolean onLongPress(Key key) { return super.onLongPress(key); } } keyboard.xml <?xml version="1.0" encoding="utf-8"?> <Keyboard xmlns:android="http://schemas.android.com/apk/res/android" android:keyWidth="10%p" android:horizontalGap="0px" android:verticalGap="0px" android:keyHeight="@dimen/key_height" > <Row android:rowEdgeFlags="bottom"> <Key android:codes="-3" android:keyLabel="Close" android:keyWidth="20%p" android:keyEdgeFlags="left"/> <Key android:codes="10" android:keyLabel="Return" android:keyWidth="20%p" android:keyEdgeFlags="right"/> </Row> </Keyboard> input.xml <?xml version="1.0" encoding="utf-8"?> <com.android.jt.gestureIME.GestureKeyboardView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gkeyboard" android:layout_alignParentBottom="true" android:layout_width="fill_parent" android:layout_height="wrap_content" />

    Read the article

  • Android Extend BaseExpandableListAdapter

    - by Robert Mills
    I am trying to extend the BaseExpandableListAdapter, however when once I view the list and I select one of the elements to expand, the order of the list gets reversed. For example, if I have a list with 4 elements and select the 1st element, the order (from top to bottom) is now 4, 3, 2, 1 with the 4th element (now at the top) expanded. If I unexpand the 4th element the order reverts to 1, 2, 3, 4 with no expanded elements. Here is my implementation:`public class SensorExpandableAdapter extends BaseExpandableListAdapter { private static final int FILTER_POSITION = 0; private static final int FUNCTION_POSITION = 1; private static final int NUMBER_OF_CHILDREN = 2; ArrayList mParentGroups; private Context mContext; private LayoutInflater mInflater; public SensorExpandableAdapter(ArrayList<SensorType> parentGroup, Context context) { mParentGroups = parentGroup; mContext = context; mInflater = LayoutInflater.from(mContext); } @Override public Object getChild(int groupPosition, int childPosition) { // TODO Auto-generated method stub if(childPosition == FILTER_POSITION) return "filter"; else return "function"; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if(convertView == null) { //do something convertView = (RelativeLayout)mInflater.inflate(R.layout.sensor_row_list_item, parent, false); if(childPosition == FILTER_POSITION) { ((CheckBox)convertView.findViewById(R.id.chkTextAddFilter)).setText("Add Filter"); } else { ((CheckBox)convertView.findViewById(R.id.chkTextAddFilter)).setText("Add Function"); ((CheckBox)convertView.findViewById(R.id.chkTextAddFilter)).setEnabled(false); } } return convertView; } @Override public int getChildrenCount(int groupPosition) { // TODO Auto-generated method stub return NUMBER_OF_CHILDREN; } @Override public Object getGroup(int groupPosition) { return mParentGroups.get(groupPosition); } @Override public int getGroupCount() { // TODO Auto-generated method stub return mParentGroups.size(); } @Override public long getGroupId(int groupPosition) { // TODO Auto-generated method stub return groupPosition; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if(convertView == null) { convertView = mInflater.inflate(android.R.layout.simple_expandable_list_item_1, parent, false); TextView tv = ((TextView)convertView.findViewById(android.R.id.text1)); tv.setText(mParentGroups.get(groupPosition).toString()); } return convertView; } @Override public boolean hasStableIds() { // TODO Auto-generated method stub return true; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { // TODO Auto-generated method stub return true; } } ` I just need to take a simple ArrayList of my own SensorType class. The children are the same for all classes, just two. Also, how do I go about making the parent in each group LongClickable? I have tried in my ExpandableListActivity with this getExpandableListView().setOnLongClickableListener() ... and on the parent TextView set its OnLongClickableListener but neither works. Any help on either of these is greatly appreciated!

    Read the article

  • Blackberry (Java) - Can't get KeyListener to work

    - by paullb
    I am trying to get the KeyListener working for Blackberry, but none of the Dialogs pop up indicating that a key has been pressed (see code below, each action has a dialog popup in them). Any ideas on what i might be doing wrong? public class CityInfo extends UiApplication implements KeyListener { static CityInfo application; public static void main(String[] args) { //create a new instance of the application //and start the application on the event thread application.enterEventDispatcher(); } public CityInfo() { //display a new screen application = new CityInfo(); pushScreen(new WorkflowDisplayScreen()); this.addKeyListener(this); } public boolean keyChar(char arg0, int arg1, int arg2) { // TODO Auto-generated method stub Dialog.alert("key pressed : " + arg0); return true; } public boolean keyDown(int keycode, int time) { // TODO Auto-generated method stub Dialog.alert("keyDown : " + keycode); return false; } public boolean keyRepeat(int keycode, int time) { // TODO Auto-generated method stub Dialog.alert("keyRepeat : " + keycode); return false; } public boolean keyStatus(int keycode, int time) { // TODO Auto-generated method stub Dialog.alert("keyStatus : " + keycode); return false; } public boolean keyUp(int keycode, int time) { Dialog.alert("keyUp : " + keycode); // TODO Auto-generated method stub return false; } } I also tried implementing keyChar on the MainScreen class but that did not yield any results either.

    Read the article

  • How to add OnClickListener in ViewPager

    - by Erdem Azakli
    I have problem with ViewPager and can't find answer.I want to Toast a message when pictures(view) clicked. I can't make, please help me. Example: click on the picture1 --Message"Picture1" click on the picture2 --Message"Picture2" Thanks a lot, Mypageradapter; package com.example.pictures; import android.content.Context; import android.media.AudioManager; import android.os.Parcelable; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; public class MyPagerAdapter extends PagerAdapter{ public int getCount() { return 6; } public Object instantiateItem(View collection, int position) { View view=null; LayoutInflater inflater = (LayoutInflater) collection.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); int resId = 0; switch (position) { case 0: resId = R.layout.picture1; view = inflater.inflate(resId, null); break; case 1: resId = R.layout.picture2; view = inflater.inflate(resId, null); break; case 2: resId = R.layout.picture3; view = inflater.inflate(resId, null); break; case 3: resId = R.layout.picture4; view = inflater.inflate(resId, null); break; case 4: resId = R.layout.picture5; view = inflater.inflate(resId, null); break; case 5: resId = R.layout.picture6; view = inflater.inflate(resId, null); break; } ((ViewPager) collection).addView(view, 0); return view; } @SuppressWarnings("unused") private Context getApplicationContext() { // TODO Auto-generated method stub return null; } private void setVolumeControlStream(int streamMusic) { // TODO Auto-generated method stub } @SuppressWarnings("unused") private Context getBaseContext() { // TODO Auto-generated method stub return null; } @SuppressWarnings("unused") private PagerAdapter findViewById(int myfivepanelpager) { // TODO Auto-generated method stub return null; } @Override public void destroyItem(View arg0, int arg1, Object arg2) { ((ViewPager) arg0).removeView((View) arg2); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == ((View) arg1); } @Override public Parcelable saveState() { return null; } public static Integer getItem(int position) { // TODO Auto-generated method stub return null; } } OnPageChangeListener; package com.example.pictures; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.widget.Button; import android.widget.Toast; public class Pictures extends Activity implements OnPageChangeListener{ SoundManager snd; int sound1,sound2,sound3; View view=null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.picturespage); MyPagerAdapter adapter = new MyPagerAdapter(); ViewPager myPager = (ViewPager) findViewById(R.id.myfivepanelpager); myPager.setAdapter(adapter); myPager.setCurrentItem(0); myPager.setOnPageChangeListener(this); snd = new SoundManager(this); sound1 = snd.load(R.raw.sound1); sound2 = snd.load(R.raw.sound2); sound3 = snd.load(R.raw.sound3); } public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub } public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } public void onPageSelected(int position) { // TODO Auto-generated method stub switch (position) { case 0: snd.play(sound1); break; case 1: snd.play(sound2); break; case 2: snd.play(sound3); break; case 3: Toast.makeText(this, "1", Toast.LENGTH_SHORT).show(); break; case 4: Toast.makeText(this, "2", Toast.LENGTH_SHORT).show(); break; case 5: Toast.makeText(this, "3", Toast.LENGTH_SHORT).show(); break; } } };

    Read the article

  • Display HttpResponse (string from Handler) in new WebView

    - by datguywhowanders
    I have the following code in a form's submit button onClickListener: String action, user, pwd, user_field, pwd_field; action = "theURL"; user_field = "id"; pwd_field = "pw"; user = "username"; pwd = "password!!"; List<NameValuePair> myList = new ArrayList<NameValuePair>(); myList.add(new BasicNameValuePair(user_field, user)); myList.add(new BasicNameValuePair(pwd_field, pwd)); HttpParams params = new BasicHttpParams(); HttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(action); HttpResponse end = null; String endResult = null; try { post.setEntity(new UrlEncodedFormEntity(myList)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { HttpResponse response = client.execute(post); end = response; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } BasicResponseHandler myHandler = new BasicResponseHandler(); try { endResult = myHandler.handleResponse(end); } catch (HttpResponseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } How can I take the resulting string (endResult) and start a new activity using an intent that will open webview and load the html?

    Read the article

  • How do you handle options that can't be used together with OptionParser?

    - by Joel
    My Python script (for todo lists) is started from the command line like this: todo [options] <command> [command-options] Some options can not be used together, for example todo add --pos=3 --end "Ask Stackoverflow" would specify both the third position and the end of the list. Likewise todo list --brief --informative would confuse my program about being brief or informative. Since I want to have quite a powerful option control, cases like these will be a bunch, and new ones will surely arise in the future. If a users passes a bad combination of options, I want to give an informative message, preferably along with the usage help provided by optparse. Currently I handle this with an if-else statement that I find really ugly and poor. My dream is to have something like this in my code: parser.set_not_allowed(combination=["--pos", "--end"], message="--pos and --end can not be used together") and the OptionParser would use this when parsing the options. Since this doesn't exist as far as I know, I ask the SO community: How do you handle this?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >