Search Results

Search found 514 results on 21 pages for 'runnable'.

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

  • Does SetThreadPriority cause thread reschedulling?

    - by Suma
    Consider following situation, assuming single CPU system: thread A is running with a priority THREAD_PRIORITY_NORMAL, signals event E thread B with a priority THREAD_PRIORITY_LOWEST is waiting for an event E (Note: at this point the thread is not scheduled because it is runnable, but A is higher priority and runnable as well) thread A calls SetThreadPriority(B, THREAD_PRIORITY_ABOVE_NORMAL) Is thread B re-scheduled immediately to run, or is thread A allowed to continue until current time-slice is over, and B is scheduled only once a new time-slice has begun? I would be interested to know the answer for WinXP, Vista and Win7, if possible. Note: the scenario above is simplified from my real world code, where multiple threads are running on multiple cores, but the main object of the question stays: does SetThreadPriority cause thread scheduling to happen?

    Read the article

  • Can't open DDMS

    - by Emerald214
    When I open a standalone DDMS besides Eclipse, it generates the below error. hieund@hieund:~$ ddms 01:51:58 E/ddms: Could not open Selected VM debug port (8700). Make sure you do not have another instance of DDMS or of the eclipse plugin running. If it's being used by something else, choose a new port number in the preferences. (DDMS:6904): Gtk-WARNING **: gtk_widget_size_allocate(): attempt to allocate widget with width -5 and height 17 (DDMS:6904): Gtk-WARNING **: gtk_widget_size_allocate(): attempt to allocate widget with width -5 and height 17 01:52:18 E/DDMS: device offline com.android.ddmlib.AdbCommandRejectedException: device offline at com.android.ddmlib.AdbHelper.setDevice(AdbHelper.java:736) at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:373) at com.android.ddmlib.Device.executeShellCommand(Device.java:364) at com.android.ddmuilib.SysinfoPanel.loadFromDevice(SysinfoPanel.java:159) at com.android.ddmuilib.SysinfoPanel.deviceSelected(SysinfoPanel.java:126) at com.android.ddmuilib.SelectionDependentPanel.deviceSelected(SelectionDependentPanel.java:52) at com.android.ddms.UIThread.selectionChanged(UIThread.java:1721) at com.android.ddmuilib.DevicePanel.notifyListeners(DevicePanel.java:752) at com.android.ddmuilib.DevicePanel.notifyListeners(DevicePanel.java:740) at com.android.ddmuilib.DevicePanel.access$1100(DevicePanel.java:56) at com.android.ddmuilib.DevicePanel$1.widgetSelected(DevicePanel.java:357) at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source) at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source) at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source) at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source) at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source) at com.android.ddms.UIThread.runUI(UIThread.java:517) at com.android.ddms.Main.main(Main.java:116) 01:52:32 E/ddms: shutting down due to uncaught exception 01:52:32 E/ddms: Failed to execute runnable (java.lang.ArrayIndexOutOfBoundsException: -1) org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.ArrayIndexOutOfBoundsException: -1) at org.eclipse.swt.SWT.error(Unknown Source) at org.eclipse.swt.SWT.error(Unknown Source) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Unknown Source) at org.eclipse.swt.widgets.Display.runAsyncMessages(Unknown Source) at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source) at com.android.ddms.UIThread.runUI(UIThread.java:517) at com.android.ddms.Main.main(Main.java:116) Caused by: java.lang.ArrayIndexOutOfBoundsException: -1 at org.eclipse.jface.viewers.AbstractTableViewer$VirtualManager.resolveElement(AbstractTableViewer.java:100) at org.eclipse.jface.viewers.AbstractTableViewer$1.handleEvent(AbstractTableViewer.java:70) at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source) at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source) at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source) at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source) at org.eclipse.swt.widgets.Table.checkData(Unknown Source) at org.eclipse.swt.widgets.Table.cellDataProc(Unknown Source) at org.eclipse.swt.widgets.Display.cellDataProc(Unknown Source) at org.eclipse.swt.internal.gtk.OS._gtk_list_store_append(Native Method) at org.eclipse.swt.internal.gtk.OS.gtk_list_store_append(Unknown Source) at org.eclipse.swt.widgets.Table.setItemCount(Unknown Source) at org.eclipse.jface.viewers.TableViewer.doSetItemCount(TableViewer.java:217) at org.eclipse.jface.viewers.AbstractTableViewer.internalVirtualRefreshAll(AbstractTableViewer.java:661) at org.eclipse.jface.viewers.AbstractTableViewer.internalRefresh(AbstractTableViewer.java:635) at org.eclipse.jface.viewers.AbstractTableViewer.internalRefresh(AbstractTableViewer.java:620) at org.eclipse.jface.viewers.StructuredViewer$7.run(StructuredViewer.java:1430) at org.eclipse.jface.viewers.StructuredViewer.preservingSelection(StructuredViewer.java:1365) at org.eclipse.jface.viewers.StructuredViewer.preservingSelection(StructuredViewer.java:1328) at org.eclipse.jface.viewers.StructuredViewer.refresh(StructuredViewer.java:1428) at org.eclipse.jface.viewers.ColumnViewer.refresh(ColumnViewer.java:537) at org.eclipse.jface.viewers.StructuredViewer.refresh(StructuredViewer.java:1387) at com.android.ddmuilib.logcat.LogCatPanel$LogCatTableRefresherTask.run(LogCatPanel.java:1000) at org.eclipse.swt.widgets.RunnableLock.run(Unknown Source) ... 5 more I tried to change port for DDMS in Eclipse but it still doesn't work.

    Read the article

  • How to unicode Myanmar texts on Java? [closed]

    - by Spacez Ly Wang
    I'm just beginner of Java. I'm trying to unicode (display) correctly Myanmar texts on Java GUI ( Swing/Awt ). I have four TrueType fonts which support Myanmar unicode texts. There are Myanmar3, Padauk, Tharlon, Myanmar Text ( Window 8 built-in ). You may need the fonts before the code. Google the fonts, please. Each of the fonts display on Java GUI differently and incorrectly. Here is the code for GUI Label displaying myanmar texts: ++++++++++++++++++++++++ package javaapplication1; import javax.swing.JFrame; import javax.swing.JTextField; public class CusFrom { private static void createAndShowGUI() { JFrame frame = new JFrame("Hello World Swing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); String s = "\u1015\u102F \u103C\u1015\u102F"; JLabel label = new JLabel(s); label.setFont(new java.awt.Font("Myanmar3", 0, 20));// font insert here, Myanmar Text, Padauk, Myanmar3, Tharlon frame.getContentPane().add(label); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } } ++++++++++++++++++++++++ Outputs vary. See the pictures: Myanmar3 IMG Padauk IMG Tharlon IMG Myanmar Text IMG What is the correct form? (on notepad) Well, next is the code for GUI Textfield inputting Myanmar texts: ++++++++++++++++++++++++ package javaapplication1; import javax.swing.JFrame; import javax.swing.JTextField; public class XusForm { private static void createAndShowGUI() { JFrame frame = new JFrame("Frame Title"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTextField textfield = new JTextField(); textfield.setFont(new java.awt.Font("Myanmar3", 0, 20)); frame.getContentPane().add(textfield); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } } ++++++++++++++++++++++++ Outputs vary when I input keys( unicode text ) on keyboards. Myanmar Text Output IMG Padauk Output IMG Myanmar3 Output IMG Tharlon Output IMG Those fonts work well on Linux when opening text files with Text Editor application. My Question is how to unicode Myanmar texts on Java GUI. Do I need additional codes left to display well? Or Does Java still have errors? The fonts display well on Web Application (HTML, CSS) but I'm not sure about displaying on Java Web Application.

    Read the article

  • Problems with X11GraphicsDevice on Suse 11

    - by Daniel
    Hi, On servers running Suse 11 I'm experiencing hangups in sun.awt.X11GraphicsDevice.getDoubleBufferVisuals(Native Method) when connecting via Citrix (and setting DISPLAY to localhost:11.0). Running exactly the same code in exactly the same environment, excepth through Exceed (with DISPLAY set to my workstation's IP) it runs like clockwork. The error is not intermittent, it happens every time Reinstalling the OS does not help Can not reproduce it on Suse 10 This is what the main thread stack looks like: [junit] "main" prio=10 tid=0x0000000040112000 nid=0x6acc runnable [0x00002b9f909ae000] [junit] java.lang.Thread.State: RUNNABLE [junit] at sun.awt.X11GraphicsDevice.getDoubleBufferVisuals(Native Method) [junit] at sun.awt.X11GraphicsDevice.makeDefaultConfiguration(X11GraphicsDevice.java:208) [junit] at sun.awt.X11GraphicsDevice.getDefaultConfiguration(X11GraphicsDevice.java:182) [junit] - locked <0x00002b9fed6b8e70 (a java.lang.Object) [junit] at sun.awt.X11.XToolkit.(XToolkit.java:92) [junit] at java.lang.Class.forName0(Native Method) [junit] at java.lang.Class.forName(Class.java:169) [junit] at java.awt.Toolkit$2.run(Toolkit.java:834) [junit] at java.security.AccessController.doPrivileged(Native Method) [junit] at java.awt.Toolkit.getDefaultToolkit(Toolkit.java:826) [junit] - locked <0x00002b9f94b8ada0 (a java.lang.Class for java.awt.Toolkit) [junit] at java.awt.Toolkit.getEventQueue(Toolkit.java:1676) [junit] at java.awt.EventQueue.invokeLater(EventQueue.java:954) [junit] at javax.swing.SwingUtilities.invokeLater(SwingUtilities.java:1264) ... Has anyone experienced something similar? Could this be a problem in Suse 11's display handling? I'm thankful for any input at this point - I'm fresh out of ideas :)

    Read the article

  • Multiple threads stuck on Tomcat behind Apache mod_proxy

    - by Eddy
    we just took a break at butting our collective heads against this maddening problem we're having. Basically this brand new deployment of Tomcat 6.0.36 crawls down to a halt every couple minutes with many of the worker threads stuck as in the example snippet; only after a while the server gets "unstuck" for another couple minutes. The previous Tomcat works a charm though, but keeping it is not really an option... On netstat, we also see a lot of FIN_WAIT and FIN2_WAIT. "catalina-exec-25" daemon prio=10 tid=0x000000004f9d4000 nid=0x7459 runnable [0x0000000044567000] java.lang.Thread.State: RUNNABLE at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92) at java.net.SocketOutputStream.write(SocketOutputStream.java:136) at org.apache.coyote.http11.InternalOutputBuffer.realWriteBytes(InternalOutputBuffer.java:756) at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:448) at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:363) at org.apache.coyote.http11.InternalOutputBuffer$OutputStreamOutputBuffer.doWrite(InternalOutputBuffer.java:780) at org.apache.coyote.http11.filters.IdentityOutputFilter.doWrite(IdentityOutputFilter.java:118) at org.apache.coyote.http11.InternalOutputBuffer.doWrite(InternalOutputBuffer.java:593) at org.apache.coyote.Response.doWrite(Response.java:560) at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:364) at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:448) at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:318) at org.apache.catalina.connector.OutputBuffer.close(OutputBuffer.java:274) at org.apache.catalina.connector.Response.finishResponse(Response.java:493) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:317) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:396) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662) Any idea? Eddy

    Read the article

  • High data on recv-q buffer and thread lock on java.io.BufferedInputStream in linux

    - by Sagar Patel
    We have a java application running on linux (ubuntu server). We have been facing high recv-q problem since quite some time. Application gets hang and does not read data from socket every few hours. In thread dump, we have found below stack trace. "Receiver-146" daemon prio=10 tid=0x00007fb3fc010000 nid=0x7642 runnable [0x00007fb5906c5000] java.lang.Thread.State: RUNNABLE at java.net.SocketInputStream. socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:150) at java.net.SocketInputStream.read(SocketInputStream.java:121) at java.io.BufferedInputStream.fill(BufferedInputStream.java:235) at java.io.BufferedInputStream.read1(BufferedInputStream.java:275) at java.io.BufferedInputStream.read(BufferedInputStream.java:334) - locked <0x00000007688f1ff0> (a java.io.BufferedInputStream) at org.smpp.TCPIPConnection.receive(TCPIPConnection.java:413) at org.smpp.ReceiverBase.receivePDUFromConnection(ReceiverBase.java:197) at org.smpp.Receiver.receiveAsync(Receiver.java:351) at org.smpp.ReceiverBase.process(ReceiverBase.java:96) at org.smpp.util.ProcessingThread.run(ProcessingThread.java:199) at java.lang.Thread.run(Thread.java:722) We are not able to trace the exact reason behind this? Kindly help. We are using 16 core machine and load on the system is around 30-40 at the time of issue. We use command ss dst <ip> to find out recv-q. Recently we have been facing issues with recv-q size getting hung, were in receive buffer gets stuck at some point of time. But recvQ size is not decreasing and as a result we are losing a lot of hits from the other side, our application is not accepting any data.

    Read the article

  • Android ProgressDialog Progress Bar doing things in the right order

    - by FauxReal
    I just about got this, but I have a small problem in the order of things going off. Specifically, in my thread() I am setting up an array that is used by a Spinner. Problem is the Spinner is all set and done basically before my thread() is finished, so it sets itself up with a null array. How do I associate the spinners ArrayAdapter with an array that is being loaded by another thread? I've cut the code down to what I think is necessary to understand the problem, but just let me know if more is needed. The problem occurs whether or not refreshData() is called. Along the same lines, sometimes I want to call loadData() from the menu. Directly following loadData() if I try to fire a toast on the next line this causes a forceclose, which is also because of how I'm implementing ProgressDialog. THANK YOU FOR LOOKING public class CMSHome extends Activity { private static List<String> pmList = new ArrayList<String>(); // Instantiate helpers PMListHelper plh = new PMListHelper(); ProjectObjectHelper poc = new ProjectObjectHelper(); // These objects hold lists and methods for dealing with them private Employees employees; private Projects projects; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Loads data from filesystem, or webservice if necessary loadData(); // Capture spinner and associate pmList with it through ArrayAdapter spinner = (Spinner) findViewById(R.id.spinner); ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, pmList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); //---the button is wired to an event handler--- Button btn1 = (Button)findViewById(R.id.btnGetProjects); btn1.setOnClickListener(btnListAllProjectsListener); spinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); } private void loadData() { final ProgressDialog pd = ProgressDialog.show(this, "Please wait", "Loading Data...", true, false); new Thread(new Runnable(){ public void run(){ employees = plh.deserializeEmployeeData(); projects = poc.deserializeProjectData(); // Check to see if data actually loaded, if not then refresh if ((employees == null) || (projects == null)) { refreshData(); } // Load up pmList for spinner control pmList = employees.getPMList(); pd.dismiss(); } }).start(); } private void refreshData() { // Refresh data for Projects projects = poc.refreshData(); poc.saveProjectData(mCtx, projects); // Refresh data for PMList employees = plh.refreshData(); plh.savePMData(mCtx, employees); } } <---- EDIT ----- I tried changing loadData() to the following after Jims suggestion. Not sure if I did this right, still doesn't work: private void loadData() { final ProgressDialog pd = ProgressDialog.show(this, "Please wait", "Loading Data...", true, false); new Thread(new Runnable(){ public void run(){ employees = plh.deserializeEmployeeData(); projects = poc.deserializeProjectData(); // Check to see if data actually loaded, if not return false if ((employees == null) || (projects == null)) { refreshData(); } pd.dismiss(); runOnUiThread(new Runnable() { public void run(){ // Load up pmList for spinner control pmList = employees.getPMList(); } }); } }).start(); }

    Read the article

  • black screen while retrieving result from webservices in android

    - by Aswan
    Hi Folks i am using following webservices for retrieving data from server server side:.net client side:ksoap2 whenever activity start, onCreate i am using spinner for displying data returned by the webservices when this activity start it showing black screen after lunching the activity .i found black screen is coming when activity connecting to webservices How to resolve this MyCode public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { //Display the online and busy people display in spinner //people are display in relative people only(Mygroup) /* get the online and busy people who are in user group from DB*/ users_names_ids=new ParseXMLString().convertusernames(new DataParsingComm().ILGetOnlinePeoples("<spGetOnlinePeoples><UserID>"+GetCurrentUserID.id+"</UserID></spGetOnlinePeoples>")); /* create an array with the size of number of peoples whose status is online or busy */ String[] array =new String[users_names_ids.size()]; int setselction=0;// initialize the selection to 0. /* if array length is greater than zero, that means getting at least one person whose status is online or busy */ if(array.length>0){ /* Returns an enumeration on the keys of this Hashtable instance. And assigns into Enumeration instance variable */ Enumeration e= users_names_ids.keys(); /* Iterate list Enumeration until it does't has any more elements */ for(int i=0;e.hasMoreElements();i++) try{ /* get all persons names into the array list */ array[i]=e.nextElement().toString(); /* Get the ChatUserName value from the ChatInPeopleDetails preferences. And If it is in this list set selection to the index 'i' */ if(getSharedPreferences("ChatInPeopleDetails", 0).getString("ChatUserName", "").equals(array[i])) setselction=i; /* * Get the String value of Relname, that previously added with putExtra() as extended data to the parent intent * If that value is not null and exists in the array list then * set the selection to the index 'i'. * */ else if(getIntent().getStringExtra("Relname")!=null && getIntent().getStringExtra("Relname").equals(array[i])) setselction=i; }catch(Exception ex){ ex.printStackTrace(); } finally { System.gc(); System.runFinalization(); } } /* create a new array adapter with the ChatForm context and array objects */ ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(ChatForm.this,android.R.layout.simple_spinner_item, array); /* Set the layout resource to create the drop down views. */ adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); /* The Adapter is used to provide the data which backs this Spinner SpinnerUsersToChat. */ ((Spinner)findViewById(R.id.SpinnerUsersToChat)).setAdapter(adapter2); /* Get the ChatUserName value from the ChatInPeopleDetails preferences. If this value is not null*/ if(getSharedPreferences("ChatInPeopleDetails", 0).getString("ChatUserName", "") !=null) { /* Set the currently selected item of spinner based on selection variable value */ ((Spinner)findViewById(R.id.SpinnerUsersToChat)).setSelection(setselction); } /* Register a callback to be invoked when an item in this AdapterView has been selected.*/ ((Spinner)findViewById(R.id.SpinnerUsersToChat)).setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent,View v,int position,long id) { /* call getMsg() to get messages and display them*/ getMsg(); /* Causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread.*/ ((ScrollView)findViewById(R.id.ScrollView06)).post(new Runnable() { public void run() { /* This fullScroll() method will scroll the view to the bottom .*/ ((ScrollView)findViewById(R.id.ScrollView06)).fullScroll(View.FOCUS_DOWN); } }); } /* on nothing selected to do somthing . this an overridden method */ public void onNothingSelected(AdapterView<?> arg0) { } }); } catch (Exception e1) { e1.printStackTrace(); } }

    Read the article

  • java will this threading setup work or what can i be doing wrong

    - by Erik
    Im a bit unsure and have to get advice. I have the: public class MyApp extends JFrame{ And from there i do; MyServer = new MyServer (this); MyServer.execute(); MyServer is a: public class MyServer extends SwingWorker<String, Object> { MyServer is doing listen_socket.accept() in the doInBackground() and on connection it create a new class Connection implements Runnable { I have the belove DbHelper that are a singleton. It holds an Sqlite connected. Im initiating it in the above MyApp and passing references all the way in to my runnable: class Connection implements Runnable { My question is what will happen if there are two simultaneous read or `write? My thought here was the all methods in the singleton are synchronized and would put all calls in the queue waiting to get a lock on the synchronized method. Will this work or what can i change? public final class DbHelper { private boolean initalized = false; private String HomePath = ""; private File DBFile; private static final String SYSTEM_TABLE = "systemtable"; Connection con = null; private Statement stmt; private static final ContentProviderHelper instance = new ContentProviderHelper (); public static ContentProviderHelper getInstance() { return instance; } private DbHelper () { if (!initalized) { initDB(); initalized = true; } } private void initDB() { DBFile = locateDBFile(); try { Class.forName("org.sqlite.JDBC"); // create a database connection con = DriverManager.getConnection("jdbc:sqlite:J:/workspace/workComputer/user_ptpp"); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private File locateDBFile() { File f = null; try{ HomePath = System.getProperty("user.dir"); System.out.println("HomePath: " + HomePath); f = new File(HomePath + "/user_ptpp"); if (f.canRead()) return f; else { boolean success = f.createNewFile(); if (success) { System.out.println("File did not exist and was created " + HomePath); // File did not exist and was created } else { System.out.println("File already exists " + HomePath); // File already exists } } } catch (IOException e) { System.out.println("Maybe try a new directory. " + HomePath); //Maybe try a new directory. } return f; } public String getHomePath() { return HomePath; } private synchronized String getDate(){ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } public synchronized String getSelectedSystemTableColumn( String column) { String query = "select "+ column + " from " + SYSTEM_TABLE ; try { stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String value = rs.getString(column); if(value == null || value == "") return ""; else return value; } } catch (SQLException e ) { e.printStackTrace(); return ""; } finally { } return ""; } }

    Read the article

  • SQL SERVER – DMV – sys.dm_os_wait_stats Explanation – Wait Type – Day 3 of 28

    - by pinaldave
    The key Dynamic Management View (DMV) that helps us to understand wait stats is sys.dm_os_wait_stats; this DMV gives us all the information that we need to know regarding wait stats. However, the interpretation is left to us. This is a challenge as understanding wait stats can often be quite tricky. Anyway, we will cover few wait stats in one of the future articles. Today we will go over the basic understanding of the DMV. The Official Book OnLine Reference for DMV is over here: sys.dm_os_wait_stats. I suggest you all to refer this for all the accuracy. Following is a statement from the online book: “Specific types of wait times during query execution can indicate bottlenecks or stall points within the query. Similarly, high wait times, or wait counts server wide can indicate bottlenecks or hot spots in interaction query interactions within the server instance.” This is the statement which has inspired me to write this series. Let us first run the following statement from DMV. SELECT * FROM sys.dm_os_wait_stats ORDER BY wait_time_ms DESC GO Above statement will show us few of the columns. Here it is quick explanation of each of the column. wait_type – this is the name of the wait type. There can be three different kinds of wait types – resource, queue and external. waiting_tasks_count – this incremental counter is a good indication of frequent the wait is happening. If this number is very high, it is good indication for us to investigate that particular wait type. It is quite possible that the wait time is considerably low, but the frequency of the wait is much high. wait_time_ms – this is total wait accumulated for any type of wait. This is the total wait time and includes singal_wait_time_ms. max_wait_time_ms – this indicates the maximum wait type ever occurred for that particular wait type. Using this, one can estimate the intensity of the wait type in past. Again, it is not necessary that this max wait time will occur every time; so do not over invest yourself here. signal_wait_time_ms – this is the wait time when thread is marked as runnable and it gets to the running state. If the runnable queue is very long, you will find that this wait time becomes high. Additionally, please note that this DMV does not show current wait type or wait stats. This is cumulative view of the all the wait stats since server (instance) restarted or wait stats have been cleared. In future blog post, we will also cover two more DMVs which can be helpful to identify wait-related issues. ?sys.dm_os_waiting_tasks sys.dm_exec_requests Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, PostADay, SQL, SQL Authority, SQL DMV, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, SQL Wait Stats, SQL Wait Types, T SQL, Technology

    Read the article

  • jrunscript as a cross platform scripting environment

    - by user12798506
    ?????????????????????????????????????????????????????????sh????????????UNIX???????????????????sh???????????????????????????????????????????Windows????????????????? sh??????????????find?grep?sed?awk???Windows??????????????????????????????????????????????????????????????????????????????????????????????Windows???Cygwin????????????sh??????Windows??????????????Cygwin????????????????????????????????????????????JDK?????jrunscript?????JavaScript???????????????????????1?????????jrunscript??????????????????? Windows???UNIX??????????????????????? find?grep?sed?awk?????????sh???????????????Windows Script Host??????? Java????????????? ??????????????????????????????????????????????????????????(?????????????????????????????????????????) ?????????????JDK 6??????????????????????????PC????????????????JDK 6?PC????????????????????????????????????JDK????????????????????????????????????????jrunscript?????????????????????????? ?????jrunscript????JavaScript?????????????????????????????????????????? 1) Windows???UNIX????????????????? ?????????????????????????????????????????JavaScript???mytool.js???????????????????????jrunscript???????????UNIX????sh???????Windows????bat????????????????????? mytool.sh (UNIX?): #!/bin/sh bindir=$(cd $(dirname $0) && pwd) case "`uname`" in CYGWIN*) bindir=`cygpath -w "$bindir"` ;; esac jrunscript "${bindir}/mytool.js" $* mytool.bat (Windows?): @echo off set bindir=%~dp0 jrunscript "%bindir%mytool.js" %* UNIX??sh????????Cygwin???????????????????????????????????????????js??????????????UNIX?Windows??????????????????????????????? 2) jrunscript??cat, cp, find?grep?????? jrunscript???UNIX?????????????????????????????????? jrunscript JavaScript built-in functions ????UNIX??sh?????????????????????UNIX?????????????????????????????????????????src??????????java????????????enum???????java?????????????????????????????????????????????? find('src', '.*.java', function(f) { grep('enum', f); }); ???????UNIX?????????????????????????????????????????????????????????????????????????????????????????cp(from, to)??????????????????????????????????????????UNIX??????????? $ cp -r src/* tmp/ ?????????????????????????????????????????find()???????cp -r????????·?????????????????????? function cpr(fromdir, todir, pattern) { if (pattern == undefined) { pattern = ".*"; } var frdir = pathToFile(fromdir).getCanonicalPath(); find(fromdir, pattern, function(f) { // relative dir of file f from 'fromdir'. var relative = f.getParentFile().getCanonicalPath().substring(frdir.length() + 1); var dstdir = pathToFile(todir + "/" + relative); if (!dstdir.exists()) { // Create the destination dir for file f. mkdirs(dstdir); } // Copy file f to 'dstdir'. cp(f, dstdir + "/" + f.getName()); }); } java?????I/O?API??Windows?????????????"/"??????????????????????????????UNIX?Windows?????????????? ????????????exec(cmd)?????????jar???????????????????????????????????????????? $ jrunscript js> exec("jar xvf example.jar") META-INF/ ?????????????µ???B META-INF/MANIFEST.MF ???W?J???????µ???B com/ ?????????????µ???B com/example/ ?????????????µ???B com/example/Bar.class ???W?J???????µ???B com/example/dummy/ ?????????????µ???B com/example/dummy/dummy.txt ?????o???????µ???B com/example/dummy.properties ?????o???????µ???B com/example/Foo.class ???W?J???????µ???B ???exec()?????????????????????????????????????????????????????????????????Windows????????????I/O??????????????????????????????????BAT????????? errmsg.bat: for /L %%i in (1,1,50) do echo "Error Message count = %%i" 1&2 jrunscript??exec()???????????????18??????????????????????????????????? C:\tmp>jrunscript -e "exec('errmsg.bat')" C:\tmp>for /L %i in (1 1 100) do echo "Error Message count = %i" 1>&2 C:\tmp>echo "Error Message count = 1" 1>&2 : C:\tmp>echo "Error Message count = 18" 1>&2 ? ??? ???????????exec()?????????????????????????????????????????????????????????????????DataInputStream???????????????????????? $ jrunscript js this["exec"].toString() function exec(cmd) { var process = java.lang.Runtime.getRuntime().exec(cmd); var inp = new DataInputStream(process.getInputStream()); var line = null; while ((line = inp.readLine()) != null) { println(line); } process.waitFor(); $exit = process.exitValue(); } ?????????????????????????????????????????????????????exec()???????????????exec()?????????????????????????????exec()??????? function exec(cmd) { var process = java.lang.Runtime.getRuntime().exec(cmd); var stdworker = new java.lang.Runnable( {run: function() { cat(process.getInputStream()); }}); var errworker = new java.lang.Runnable( {run: function() { cat(process.getErrorStream()); }}); new java.lang.Thread(stdworker).start(); new java.lang.Thread(errworker).start(); return proc.waitFor(); } ???????????????????cat()???????????cat()?InputStreamReader?????????????????????????????????????????????????? 3) JavaScript???????????????? JavaScript?Java???????????????????????JavaScript????????????Ruby?Groovy?Scala???????????????????????????????????????????????10MB?????????????????????????????????????JavaScript????????????????????KB?????????????MB?JAR??????????????????????????JRE?JDK?????????????????????????????????????????

    Read the article

  • Sometimes Java web app hang

    - by zhongshu
    The web app occasionally get hang for about 30 seconds when user request a web page, the server's CPU and memory usage are ok, and the jstack shows: "http-9999-3" daemon prio=6 tid=0x552f3400 nid=0xf40 runnable [0x578fc000] java.lang.Thread.State: RUNNABLE at org.eclipse.jdt.internal.compiler.parser.Parser.getTypeReference(Parser.java:8354) at org.eclipse.jdt.internal.compiler.parser.Parser.consumeClassHeaderExtends(Parser.java:2125) at org.eclipse.jdt.internal.compiler.parser.Parser.consumeRule(Parser.java:5107) at org.eclipse.jdt.internal.compiler.parser.Parser.parse(Parser.java:9020) at org.eclipse.jdt.internal.compiler.parser.Parser.parse(Parser.java:9251) at org.eclipse.jdt.internal.compiler.parser.Parser.parse(Parser.java:9208) at org.eclipse.jdt.internal.compiler.parser.Parser.dietParse(Parser.java:7864) at org.eclipse.jdt.internal.compiler.Compiler.internalBeginToCompile(Compiler.java:587) at org.eclipse.jdt.internal.compiler.Compiler.beginToCompile(Compiler.java:357) at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:371) at org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:413) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:317) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:295) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:282) at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:586) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317) - locked <0x10a75fc0> (a org.apache.jasper.servlet.JspServletWrapper) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:630) at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:535) at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:472) ...... seems it's related with some jsp files, how to find the root cause? thanks.

    Read the article

  • Using Java Executor on AppEngine causes AccessControlException

    - by Drew
    How do you get java.util.concurrent.Executor or CompletionService to work on Google AppEngine? The classes are all officially white-listed, but I get a runtime security error when trying to submit asynchronous tasks. Code: // uses the async API but this factory makes it so that tasks really // happen sequentially Executor executor = java.util.concurrent.Executors.newSingleThreadExecutor(); // wrap Executor in CompletionService CompletionService<String> completionService = new ExecutorCompletionService<String>(executor); final SomeTask someTask = new SomeTask(); // this line throws exception completionService.submit(new Callable<String>(){ public String call() { return someTask.doNothing("blah"); } }); // alternately, send Runnable task directly to Executor, // which also throws an exception executor.execute(new Runnable(){ public void run() { someTask.doNothing("blah"); } }); } private class SomeTask{ public String doNothing(String message){ return message; } } Exception: java.security.AccessControlException: access denied (java.lang.RuntimePermission modifyThreadGroup) at java.security.AccessControlContext.checkPermission(AccessControlContext.java:323) at java.security.AccessController.checkPermission(AccessController.java:546) at java.lang.SecurityManager.checkPermission(SecurityManager.java:532) at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkPermission(DevAppServerFactory.java:166) at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkAccess(DevAppServerFactory.java:191) at java.lang.ThreadGroup.checkAccess(ThreadGroup.java:288) at java.lang.Thread.init(Thread.java:332) at java.lang.Thread.(Thread.java:565) at java.util.concurrent.Executors$DefaultThreadFactory.newThread(Executors.java:542) at java.util.concurrent.ThreadPoolExecutor.addThread(ThreadPoolExecutor.java:672) at java.util.concurrent.ThreadPoolExecutor.addIfUnderCorePoolSize(ThreadPoolExecutor.java:697) at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:652) at java.util.concurrent.Executors$DelegatedExecutorService.execute(Executors.java:590) at java.util.concurrent.ExecutorCompletionService.submit(ExecutorCompletionService.java:152) This code works fine when run on Tomcat or via command-line JVM. However, it chokes in the AppEngine SDK Jetty container (tried with Eclipse plugin and the maven-gae-plugin). AppEngine is likely designed to not allow potentially dangerous programs to run, so I could see them completely disabling thread creation. However, why would Google allow you to create a class, but not allow you to call methods on it? White-listing java.util.concurrent is misleading. Is there some other way to do parallel/simultaneous/concurrent tasks on GAE?

    Read the article

  • java TrayIcon using image with transparent background

    - by Jack
    I am using the following code to set a tray icon in Windows and Linux. It works wonderful in Windows and works okay in Linux. In Linux (Ubuntu) I have my panel set to be (somewhat) transparent and when I add a GIF (with a transparent background) the background of the icon shows up all grey and ugly (see image, green diamond "!")....Any ideas on how to make the GIF image I am adding "keep" its transparent background? and the image I am using, if you'd like to test: import java.awt.*; import java.awt.event.*; public class TrayFun { static class ShowMessageListener implements ActionListener { TrayIcon trayIcon; String title; String message; TrayIcon.MessageType messageType; ShowMessageListener( TrayIcon trayIcon, String title, String message, TrayIcon.MessageType messageType) { this.trayIcon = trayIcon; this.title = title; this.message = message; this.messageType = messageType; } public void actionPerformed(ActionEvent e) { trayIcon.displayMessage(title, message, messageType); } } public static void main(String args[]) { Runnable runner = new Runnable() { public void run() { if (SystemTray.isSupported()) { final SystemTray tray = SystemTray.getSystemTray(); Image image = Toolkit.getDefaultToolkit().getImage("green_info.png"); PopupMenu popup = new PopupMenu(); final TrayIcon trayIcon = new TrayIcon(image, "The Tip Text", popup); trayIcon.setImageAutoSize(true); MenuItem item = new MenuItem("Close"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { tray.remove(trayIcon); } }); popup.add(item); try { tray.add(trayIcon); } catch (AWTException e) { System.err.println("Can't add to tray"); } } else { System.err.println("Tray unavailable"); } } }; EventQueue.invokeLater(runner); } }

    Read the article

  • Using Google Visualization in GWT 2.0

    - by nick
    I'm working on learning GWT (total newb) and have a question regarding the Visualiztion API provided by Google. This page: http://code.google.com/p/gwt-google-apis/wiki/VisualizationGettingStarted Describes getting started with a pie chart (which is what I need). However I'm trying to do this in a composite UI using UiBinder. To that end I don't know how to handle the callback correctly that is shown: public class SimpleViz implements EntryPoint { public void onModuleLoad() { // Create a callback to be called when the visualization API // has been loaded. Runnable onLoadCallback = new Runnable() { public void run() { Panel panel = RootPanel.get(); // Create a pie chart visualization. PieChart pie = new PieChart(createTable(), createOptions()); pie.addSelectHandler(createSelectHandler(pie)); panel.add(pie); } }; // Load the visualization api, passing the onLoadCallback to be called // when loading is done. VisualizationUtils.loadVisualizationApi(onLoadCallback, PieChart.PACKAGE); } My First assumption is this would go in the UiBinder constructor, correct? Yet this assumes that I want to place the element in the RootLayoutPanel, and I don't. I can't see an elegant and obvious way of placing it in the binder. I submit that even this guess may be wrong. Any ideas from the experts?

    Read the article

  • No output from exception

    - by Grasper
    Why does this code not print an exception stack trace? import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Playground { /** * @param args */ public static void main(String[] args) { startThread(); } private static void startThread() { ScheduledExecutorService timer = Executors .newSingleThreadScheduledExecutor(); Runnable r = new Runnable() { int dummyInt = 0; boolean dummyBoolean = false; @Override public void run() { dummyInt = Integer.parseInt("AAAA"); if (dummyBoolean) { dummyBoolean= false; } else { dummyBoolean= true; } } }; timer.scheduleAtFixedRate(r, 0, 100, TimeUnit.MILLISECONDS); } } How can I get it to? I would expect to see this: java.lang.NumberFormatException: For input string: "AAAA" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at Playground$1.run(Playground.java:25) at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) at java.util.concurrent.FutureTask$Sync.innerRunAndReset(Unknown Source) at java.util.concurrent.FutureTask.runAndReset(Unknown Source) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(Unknown Source) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(Unknown Source) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source)

    Read the article

  • Google App Engine: Unit testing concurrent access to memcache

    - by Phuong Nguyen de ManCity fan
    Would you guys show me a way to simulating concurrent access to memcache on Google App Engine? I'm trying with LocalServiceTestHelpers and threads but don't have any luck. Every time I try to access Memcache within a thread, then I get this error: ApiProxy$CallNotFoundException: The API package 'memcache' or call 'Increment()' was not found I guess that the testing library of GAE SDK tried to mimic the real environment and thus setup the environment for only one thread (the thread that running the test) which cannot be seen by other thread. Here is a piece of code that can reproduce the problem package org.seamoo.cache.memcacheImpl; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.google.appengine.api.memcache.MemcacheService; import com.google.appengine.api.memcache.MemcacheServiceFactory; import com.google.appengine.tools.development.testing.LocalMemcacheServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; public class MemcacheTest { LocalServiceTestHelper helper; public MemcacheTest() { LocalMemcacheServiceTestConfig memcacheConfig = new LocalMemcacheServiceTestConfig(); helper = new LocalServiceTestHelper(memcacheConfig); } /** * */ @BeforeMethod public void setUp() { helper.setUp(); } /** * @see LocalServiceTest#tearDown() */ @AfterMethod public void tearDown() { helper.tearDown(); } @Test public void memcacheConcurrentAccess() throws InterruptedException { final MemcacheService service = MemcacheServiceFactory.getMemcacheService(); Runnable runner = new Runnable() { @Override public void run() { // TODO Auto-generated method stub service.increment("test-key", 1L, 1L); try { Thread.sleep(200L); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } service.increment("test-key", 1L, 1L); } }; Thread t1 = new Thread(runner); Thread t2 = new Thread(runner); t1.start(); t2.start(); while (t1.isAlive()) { Thread.sleep(100L); } Assert.assertEquals((Long) (service.get("test-key")), new Long(4L)); } }

    Read the article

  • Reason for Null pointer Exception

    - by Rahul Varma
    Hi, I cant figure out why my program is showing null pointer exception. Plz help me...Here's the program... public class MusicListActivity extends Activity { List<HashMap<String, String>> songNodeDet = new ArrayList<HashMap<String,String>>(); HashMap<?,?>[] songNodeWeb; XMLRPCClient client; String logInSess; ArrayList<String> paths=new ArrayList<String>(); public ListAdapter adapter ; Object[] websongListObject; List<SongsList> SngList=new ArrayList<SongsList>(); Runnable r; ProgressDialog p; ListView lv; String s; @Override public void onCreate(Bundle si){ super.onCreate(si); setContentView(R.layout.openadiuofile); lv=(ListView)findViewById(R.id.list1); r=new Runnable(){ public void run(){ try{ getSongs(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (XMLRPCException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; Thread t=new Thread(r,"background"); t.start(); Log.e("***","process over"); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); } private Runnable returnRes = new Runnable() { @Override public void run() { Log.d("handler","handler"); removeDialog(0); p.dismiss(); list(); } }; public void list() { Log.d("#####","#####"); LayoutInflater inflater=getLayoutInflater(); String[] from={}; int[] n={}; adapter=new SongsAdapter(getApplicationContext(),songNodeDet,R.layout.row,from,n,inflater); lv.setAdapter(adapter);} private Handler handler = new Handler() { public void handleMessage(Message msg){ Log.d("*****","handler"); removeDialog(0); p.dismiss(); } }; public void webObjectList(Object[] imgListObj,String logInSess) throws XMLRPCException{ songNodeWeb = new HashMap<?,?>[imgListObj.length]; if(imgListObj!=null){ Log.e("completed","completed"); for(int i=0;i<imgListObj.length;i++){ //imgListObj.length songNodeWeb[i]=(HashMap<?,?>)imgListObj[i]; String nodeid=(String) songNodeWeb[i].get("nid"); break; Log.e("img",i+"completed"); HashMap<String,String> nData=new HashMap<String,String>(); nData.put("nid",nodeid); Object nodeget=client.call("node.get",logInSess,nodeid); HashMap<?,?> imgNode=(HashMap<?,?>)nodeget; String titleName=(String) imgNode.get("titles"); String movieName=(String) imgNode.get("album"); String singerName=(String) imgNode.get("artist"); nData.put("titles", titleName); nData.put("album", movieName); nData.put("artist", singerName); Object[] imgObject=(Object[])imgNode.get("field_image"); HashMap<?,?>[] imgDetails=new HashMap<?,?>[imgObject.length]; imgDetails[0]=(HashMap<?, ?>)imgObject[0]; String path=(String) imgDetails[0].get("filepath"); if(path.contains(" ")){ path=path.replace(" ", "%20"); } String imgPath="http://www.gorinka.com/"+path; paths.add(imgPath); nData.put("path", imgPath); Log.e("my path",path); String mime=(String)imgDetails[0].get("filemime"); nData.put("mime", mime); SongsList songs=new SongsList(titleName,movieName,singerName,imgPath,imgPath); SngList.add(i,songs); songNodeDet.add(i,nData); } Log.e("paths values",paths.toString()); // return imgNodeDet; handler.sendEmptyMessage(0); } } public void getSongs() throws MalformedURLException, XMLRPCException { String ur="http://www.gorinka.com/?q=services/xmlrpc"; URL u=new URL(ur); client = new XMLRPCClient(u); //Connecting to the website HashMap<?, ?> siteConn =(HashMap<?, ?>) client.call("system.connect"); // Getting initial sessio id String initSess=(String)siteConn.get("sessid"); //Login to the site using session id HashMap<?, ?> logInConn =(HashMap<?, ?>) client.call("user.login",initSess,"prakash","stellentsoft2009"); //Getting Login sessid logInSess=(String)logInConn.get("sessid"); websongListObject =(Object[]) client.call("nodetype.get",logInSess,""); webObjectList(websongListObject,logInSess); Log.d("webObjectList","webObjectList"); runOnUiThread(returnRes); } } Here's the Adapter associated... public class SongsAdapter extends SimpleAdapter{ static List<HashMap<String,String>> songsList; Context context; LayoutInflater inflater; public SongsAdapter(Context context,List<HashMap<String,String>> imgListWeb,int layout,String[] from,int[] to,LayoutInflater inflater) { super(context,songsList,layout,from,to); this.songsList=songsList; this.context=context; this.inflater=inflater; // TODO Auto-generated constructor stub } @Override public View getView(int postition,View convertView,ViewGroup parent)throws java.lang.OutOfMemoryError{ try { View v = ((LayoutInflater) inflater).inflate(R.layout.row,null); ImageView images=(ImageView)v.findViewById(R.id.image); TextView tvTitle=(TextView)v.findViewById(R.id.text1); TextView tvAlbum=(TextView)v.findViewById(R.id.text2); TextView tvArtist=(TextView)v.findViewById(R.id.text3); HashMap<String,String> songsHash=songsList.get(postition); String path=songsHash.get("path"); String title=songsHash.get("title"); String album=songsHash.get("album"); String artist=songsHash.get("artist"); String imgPath=path; final ImageView imageView = (ImageView) v.findViewById(R.id.image); AsyncImageLoaderv asyncImageLoader=new AsyncImageLoaderv(); Bitmap cachedImage = asyncImageLoader.loadDrawable(imgPath, new AsyncImageLoaderv.ImageCallback() { public void imageLoaded(Bitmap imageDrawable, String imageUrl) { imageView.setImageBitmap(imageDrawable); } }); imageView.setImageBitmap(cachedImage); tvTitle.setText(title); tvAlbum.setText(album); tvArtist.setText(artist); return v; } catch(Exception e){ Log.e("error",e.toString()); } return null; } public static Bitmap loadImageFromUrl(String url) { InputStream inputStream;Bitmap b; try { inputStream = (InputStream) new URL(url).getContent(); BitmapFactory.Options bpo= new BitmapFactory.Options(); bpo.inSampleSize=2; b=BitmapFactory.decodeStream(inputStream, null,bpo ); return b; } catch (IOException e) { throw new RuntimeException(e); } } } Here is what logcat is showing... 04-23 16:02:02.211: ERROR/completed(1450): completed 04-23 16:02:02.211: ERROR/paths values(1450): [] 04-23 16:02:02.211: DEBUG/*****(1450): handler 04-23 16:02:02.211: DEBUG/AndroidRuntime(1450): Shutting down VM 04-23 16:02:02.211: WARN/dalvikvm(1450): threadid=3: thread exiting with uncaught exception (group=0x4001aa28) 04-23 16:02:02.222: ERROR/AndroidRuntime(1450): Uncaught handler: thread main exiting due to uncaught exception 04-23 16:02:02.241: DEBUG/webObjectList(1450): webObjectList 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): java.lang.NullPointerException 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at com.stellent.gorinka.MusicListActivity$2.handleMessage(MusicListActivity.java:81) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at android.os.Handler.dispatchMessage(Handler.java:99) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at android.os.Looper.loop(Looper.java:123) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at android.app.ActivityThread.main(ActivityThread.java:4203) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at java.lang.reflect.Method.invokeNative(Native Method) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at java.lang.reflect.Method.invoke(Method.java:521) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549) 04-23 16:02:02.252: ERROR/AndroidRuntime(1450): at dalvik.system.NativeStart.main(Native Method) I have declared the getter and setter methods in a seperate claa named SongsList. Plz help me determine the problem...

    Read the article

  • Cannot run a JUnit test case containing threads from Eclipse

    - by Parag
    I am running JUnit test case from Eclipse 3.4.1 . This test case creates a class which starts a thread to do some stuff. When the test method ends it seems that Eclipse is forcibly shutting down the thread. If I run the same test from the command line, then the thread runs properly. Somehow I do not remember running into such problems with Eclipse before. Is this something that was always present in Eclipse or did they add it in 3.4.x ? Here is an example: When I run this test from Eclipse, I get a few printts of the cnt (till about 1800) and then the test case is terminated utomatically. However, if I run the main method, which starts JUnit's TestRunner, then the thread counts indefinetely. import junit.framework.TestCase; import junit.textui.TestRunner; /** * This class shows that Eclipses JUnit test case runner will forcibly * terminate all running threads * * @author pshah * */ public class ThreadTest extends TestCase { static Runnable run = new Runnable() { public void run() { int cnt = 0; while(true) System.out.println(cnt++); } }; public void testThread() { Thread t = new Thread(run); t.start(); } public static void main(String args[]) { TestRunner runner = new TestRunner(); runner.run(ThreadTest.class); } }

    Read the article

  • Suppress Eclipse compiler errors in in a plug-in

    - by Jan Gorzny
    Hi, I'm currently working on a plug-in for Eclipse that translates some custom Java code (which doesn't necessarily run/compile), to runnable Java code. In particular, the plug-in allows code to be written using classes created or imported during the translation. In general, the pre-translation code runs/compiles fine provided the writer uses import statements at the top of their class files. However, it would be convenient for my users if it was not necessary to import these classes. At the moment, the lack of import statements results in (obvious) compiler errors. Would it be possible to empower my plug-in to either a) suppress/ignore these errors, or b) have Eclipse find these classes automatically, without the use of import statements? I should point out that the translated code would these include the required import statements--but this is not a problem for me. I'm also aware that this could lead to lazy programmers and some bad habits. To clarify, consider the following example of pre-translated code: File f = new File("Somefilename.txt"); which clearly requires the possibly imported class File. Without an import statement (import java.io.File;), Eclipse reports that File can not be resolved to a type. This is the error I'd like to hide in files pertaining to projects created for use with my plug-in. (The translated code would include import java.io.File; so that it would be runnable) In closing, I should point out I'm not necessarily looking for code (though I wouldn't be opposed to it), but rather some links to some relevant tutorials (if they exist), or helpful tips/ideas. Also, as this is my first plug-in, it's entirely possible that what I'd like to do is not possible and that I don't realize it--if this is the case, please let me know, preferably with some justification. Thanks!

    Read the article

  • Java Stop Server Thread

    - by ikurtz
    the following code is server code in my app: private int serverPort; private Thread serverThread = null; public void networkListen(int port){ serverPort = port; if (serverThread == null){ Runnable serverRunnable = new ServerRunnable(); serverThread = new Thread(serverRunnable); serverThread.start(); } else { } } public class ServerRunnable implements Runnable { public void run(){ try { //networkConnected = false; //netMessage = "Listening for Connection"; //networkMessage = new NetworkMessage(networkConnected, netMessage); //setChanged(); //notifyObservers(networkMessage); ServerSocket serverSocket = new ServerSocket(serverPort, backlog); commSocket = serverSocket.accept(); serverSocket.close(); serverSocket = null; //networkConnected = true; //netMessage = "Connected: " + commSocket.getInetAddress().getHostAddress() + ":" + //commSocket.getPort(); //networkMessage = new NetworkMessage(networkConnected, netMessage); //setChanged(); //notifyObservers(networkMessage); } catch (IOException e){ //networkConnected = false; //netMessage = "ServerRunnable Network Unavailable"; //System.out.println(e.getMessage()); //networkMessage = new NetworkMessage(networkConnected, netMessage); //setChanged(); //notifyObservers(networkMessage); } } } The code sort of works i.e. if im attempting a straight connection both ends communicate and update. The issue is while im listening for a connection if i want to quit listening then the server thread continues running and causes problems. i know i should not use .stop() on a thread so i was wondering what the solution would look like with this in mind? EDIT: commented out unneeded code.

    Read the article

  • Controlling the order of PicoContainer startup

    - by Trejkaz
    I have been tasked with doing some refactoring work on how we start up applications. Basically we have a bunch of console apps which were depending on the GUI application startup code, causing bogus dependencies which have kick-on effects for which libraries we need to ship, and which dependencies other modules need to declare. So I have written a simple startup framework where I basically just throw a bunch of Runnable objects into a list and then run them in order - and it works. But I was thinking - we already have PicoContainer in our project, so all these things that need to be run on startup could potentially be thrown into a PicoContainer, and if they implement Startable they will start... But in some cases we want to specify the ordering between them. For example, I don't want any other component writing to the log before we write a header into the log indicating that the application is starting up. I know I can introduce ordering by introducing injection dependencies, but this feels like a hack in this case - I would need to add the log header writer as a dependency for every other component which might write to the log, which isn't great at all. Nonetheless it seems like it would be nice to control the order of PicoContainer startup, so is there perhaps some other way? Alternatively I could just keep it simple and stick to my list of Runnable. It does, after all, work.

    Read the article

  • "pushModalScreen called by a non-event thread" thrown on event thread

    - by JGWeissman
    I am trying to get my Blackberry application to display a custom modal dialog, and have the opening thread wait until the user closes the dialog screen. final Screen dialog = new FullScreen(); ...// Fields are added to dialog Application.getApplication().invokeAndWait(new Runnable() { public void run() { Application.getUiApplication().pushModalScreen(dialog); } }); This is throwing an Exception which says "pushModalScreen called by a non-event thread" despite the fact that I am using invokeAndWait to call pushModalScreen from the event thread. Any ideas about what the real problem is? Here is the code to duplicate this problem: package com.test; import net.rim.device.api.ui.*; import net.rim.device.api.ui.component.*; import net.rim.device.api.ui.container.*; public class Application extends UiApplication { public static void main(String[] args) { new Application(); } private Application() { new Thread() { public void run() { Application.this.enterEventDispatcher(); } }.start(); final Screen dialog = new FullScreen(); final ButtonField closeButton = new ButtonField("Close Dialog"); closeButton.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field, int context) { Application.getUiApplication().popScreen(dialog); } }); dialog.add(closeButton); Application.getApplication().invokeAndWait(new Runnable() { public void run() { try { Application.getUiApplication().pushModalScreen(dialog); } catch (Exception e) { // To see the Exception in the debugger throw new RuntimeException(e.getMessage()); } } }); System.exit(0); } } I am using Component Package version 4.5.0.

    Read the article

  • Can it be done in a more elegant way with the Swing Timer?

    - by Roman
    Bellow is the code for the simplest GUI countdown. Can the same be done in a shorter and more elegant way with the usage of the Swing timer? import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; public class CountdownNew { static JLabel label; // Method which defines the appearance of the window. public static void showGUI() { JFrame frame = new JFrame("Simple Countdown"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); label = new JLabel("Some Text"); frame.add(label); frame.pack(); frame.setVisible(true); } // Define a new thread in which the countdown is counting down. public static Thread counter = new Thread() { public void run() { for (int i=10; i>0; i=i-1) { updateGUI(i,label); try {Thread.sleep(1000);} catch(InterruptedException e) {}; } } }; // A method which updates GUI (sets a new value of JLabel). private static void updateGUI(final int i, final JLabel label) { SwingUtilities.invokeLater( new Runnable() { public void run() { label.setText("You have " + i + " seconds."); } } ); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { showGUI(); counter.start(); } }); } }

    Read the article

  • Why is my GUI unresponsive while a SwingWorker thread runs?

    - by Starchy
    Hello, I have a SwingWorker thread with an IOBound task which is totally locking up the interface while it runs. Swapping out the normal workload for a counter loop has the same result. The SwingWorker looks basically like this: public class BackupWorker extends SwingWorker<String, String> { private static String uname = null; private static String pass = null; private static String filename = null; static String status = null; BackupWorker (String uname, String pass, String filename) { this.uname = uname; this.pass = pass; this.filename = filename; } @Override protected String doInBackground() throws Exception { BackupObject bak = newBackupObject(uname,pass,filename); return "Done!"; } } The code that kicks it off lives in a class that extends JFrame: public void actionPerformed(ActionEvent event) { String cmd = event.getActionCommand(); if (BACKUP.equals(cmd)) { SwingUtilities.invokeLater(new Runnable() { public void run() { final StatusFrame statusFrame = new StatusFrame(); statusFrame.setVisible(true); SwingUtilities.invokeLater(new Runnable() { public void run () { statusFrame.beginBackup(uname,pass,filename); } }); } }); } } Here's the interesting part of StatusFrame: public void beginBackup(final String uname, final String pass, final String filename) { worker = new BackupWorker(uname, pass, filename); worker.execute(); try { System.out.println(worker.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } So far as I can see, everything "long-running" is handled by the worker, and everything that touches the GUI on the EDT. Have I tangled things up somewhere, or am I expecting too much of SwingWorker?

    Read the article

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