Search Results

Search found 671 results on 27 pages for 'stub'.

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

  • 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

  • Anatomy of a .NET Assembly - PE Headers

    - by Simon Cooper
    Today, I'll be starting a look at what exactly is inside a .NET assembly - how the metadata and IL is stored, how Windows knows how to load it, and what all those bytes are actually doing. First of all, we need to understand the PE file format. PE files .NET assemblies are built on top of the PE (Portable Executable) file format that is used for all Windows executables and dlls, which itself is built on top of the MSDOS executable file format. The reason for this is that when .NET 1 was released, it wasn't a built-in part of the operating system like it is nowadays. Prior to Windows XP, .NET executables had to load like any other executable, had to execute native code to start the CLR to read & execute the rest of the file. However, starting with Windows XP, the operating system loader knows natively how to deal with .NET assemblies, rendering most of this legacy code & structure unnecessary. It still is part of the spec, and so is part of every .NET assembly. The result of this is that there are a lot of structure values in the assembly that simply aren't meaningful in a .NET assembly, as they refer to features that aren't needed. These are either set to zero or to certain pre-defined values, specified in the CLR spec. There are also several fields that specify the size of other datastructures in the file, which I will generally be glossing over in this initial post. Structure of a PE file Most of a PE file is split up into separate sections; each section stores different types of data. For instance, the .text section stores all the executable code; .rsrc stores unmanaged resources, .debug contains debugging information, and so on. Each section has a section header associated with it; this specifies whether the section is executable, read-only or read/write, whether it can be cached... When an exe or dll is loaded, each section can be mapped into a different location in memory as the OS loader sees fit. In order to reliably address a particular location within a file, most file offsets are specified using a Relative Virtual Address (RVA). This specifies the offset from the start of each section, rather than the offset within the executable file on disk, so the various sections can be moved around in memory without breaking anything. The mapping from RVA to file offset is done using the section headers, which specify the range of RVAs which are valid within that section. For example, if the .rsrc section header specifies that the base RVA is 0x4000, and the section starts at file offset 0xa00, then an RVA of 0x401d (offset 0x1d within the .rsrc section) corresponds to a file offset of 0xa1d. Because each section has its own base RVA, each valid RVA has a one-to-one mapping with a particular file offset. PE headers As I said above, most of the header information isn't relevant to .NET assemblies. To help show what's going on, I've created a diagram identifying all the various parts of the first 512 bytes of a .NET executable assembly. I've highlighted the relevant bytes that I will refer to in this post: Bear in mind that all numbers are stored in the assembly in little-endian format; the hex number 0x0123 will appear as 23 01 in the diagram. The first 64 bytes of every file is the DOS header. This starts with the magic number 'MZ' (0x4D, 0x5A in hex), identifying this file as an executable file of some sort (an .exe or .dll). Most of the rest of this header is zeroed out. The important part of this header is at offset 0x3C - this contains the file offset of the PE signature (0x80). Between the DOS header & PE signature is the DOS stub - this is a stub program that simply prints out 'This program cannot be run in DOS mode.\r\n' to the console. I will be having a closer look at this stub later on. The PE signature starts at offset 0x80, with the magic number 'PE\0\0' (0x50, 0x45, 0x00, 0x00), identifying this file as a PE executable, followed by the PE file header (also known as the COFF header). The relevant field in this header is in the last two bytes, and it specifies whether the file is an executable or a dll; bit 0x2000 is set for a dll. Next up is the PE standard fields, which start with a magic number of 0x010b for x86 and AnyCPU assemblies, and 0x20b for x64 assemblies. Most of the rest of the fields are to do with the CLR loader stub, which I will be covering in a later post. After the PE standard fields comes the NT-specific fields; again, most of these are not relevant for .NET assemblies. The one that is is the highlighted Subsystem field, and specifies if this is a GUI or console app - 0x20 for a GUI app, 0x30 for a console app. Data directories & section headers After the PE and COFF headers come the data directories; each directory specifies the RVA (first 4 bytes) and size (next 4 bytes) of various important parts of the executable. The only relevant ones are the 2nd (Import table), 13th (Import Address table), and 15th (CLI header). The Import and Import Address table are only used by the startup stub, so we will look at those later on. The 15th points to the CLI header, where the CLR-specific metadata begins. After the data directories comes the section headers; one for each section in the file. Each header starts with the section's ASCII name, null-padded to 8 bytes. Again, most of each header is irrelevant, but I've highlighted the base RVA and file offset in each header. In the diagram, you can see the following sections: .text: base RVA 0x2000, file offset 0x200 .rsrc: base RVA 0x4000, file offset 0xa00 .reloc: base RVA 0x6000, file offset 0x1000 The .text section contains all the CLR metadata and code, and so is by far the largest in .NET assemblies. The .rsrc section contains the data you see in the Details page in the right-click file properties page, but is otherwise unused. The .reloc section contains address relocations, which we will look at when we study the CLR startup stub. What about the CLR? As you can see, most of the first 512 bytes of an assembly are largely irrelevant to the CLR, and only a few bytes specify needed things like the bitness (AnyCPU/x86 or x64), whether this is an exe or dll, and the type of app this is. There are some bytes that I haven't covered that affect the layout of the file (eg. the file alignment, which determines where in a file each section can start). These values are pretty much constant in most .NET assemblies, and don't affect the CLR data directly. Conclusion To summarize, the important data in the first 512 bytes of a file is: DOS header. This contains a pointer to the PE signature. DOS stub, which we'll be looking at in a later post. PE signature PE file header (aka COFF header). This specifies whether the file is an exe or a dll. PE standard fields. This specifies whether the file is AnyCPU/32bit or 64bit. PE NT-specific fields. This specifies what type of app this is, if it is an app. Data directories. The 15th entry (at offset 0x168) contains the RVA and size of the CLI header inside the .text section. Section headers. These are used to map between RVA and file offset. The important one is .text, which is where all the CLR data is stored. In my next post, we'll start looking at the metadata used by the CLR directly, which is all inside the .text section.

    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

  • 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

  • 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

  • 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

  • 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

  • getJSON for dropbox data

    - by gheil.apl
    Although i used getJSON in http://jsbin.com/dbJSON/edit i have not been able to connect with any of my own made up data. i tried 4, and the example at Flickr for "cats". Only the latter worked... this is the output: {assoc: null,assoc.js: null,stub: null,stub.js: null,cat: [object Object]} i am at that "base", as i did get the image there, but db.tgu.ca/repsychal/poems/10/0512-g2g/assoc.json db.tgu.ca/repsychal/poems/10/0512-g2g/assoc.js db.tgu.ca/repsychal/poems/10/0512-g2g/stub.json db.tgu.ca/repsychal/poems/10/0512-g2g/stub.js were all invisible==null! (they are all URL, just put h t t p //: in front ... a restriction on the # of URL in a post) How do i get "my" data into the page?

    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

  • Rails 3, Devise and custom controller action

    - by Johnny Klassy
    routes.rb match 'agencies/stub' => 'agencies#stub', :via => :get resources :agencies Here's the rake routes dump agencies_stub GET /agencies/stub(.:format) {:controller=>"agencies", :action=>"stub"} agencies GET /agencies(.:format) {:action=>"index", :controller=>"agencies"} POST /agencies(.:format) {:action=>"create", :controller=>"agencies"} new_agency GET /agencies/new(.:format) {:action=>"new", :controller=>"agencies"} edit_agency GET /agencies/:id/edit(.:format) {:action=>"edit", :controller=>"agencies"} agency GET /agencies/:id(.:format) {:action=>"show", :controller=>"agencies"} PUT /agencies/:id(.:format) {:action=>"update", :controller=>"agencies"} DELETE /agencies/:id(.:format) {:action=>"destroy", :controller=>"agencies"} Devise is setup to have all agenciesroutes only accessible as admin. The call I'm testing with is http://xyz:12345@localhost:3000/agencies/stub but it doesn't authenticate properly, ie, it doesn't recognize it as admin and throws me back to the Devise login page. The creds are a valid admin account. I'm baffled and have no idea why this is happening. Any insights will be much appreciated.

    Read the article

  • What have my fellow Delphi programmers done to make Eclipse/Java more like Delphi?

    - by Robert Oschler
    I am a veteran Delphi programmer working on my first real Android app. I am using Eclipse and Java as my development environment. The thing I miss the most of course is Delphi's VCL components and the associated IDE tools for design-time editing and code creation. Fortunately I am finding Eclipse to be one hell of an IDE with it's lush context sensitive help, deep auto-complete and code wizard facilities, and other niceties. This is a huge double treat since it is free. However, here is an example of something in the Eclipse/Java environment that will give a Delphi programmer pause. I will use the simple case of adding an "on-click" code stub for an OK button. DELPHI Drop button on a form Double-click button on form and fill in the code that will fire when the button is clicked ECLIPSE Drop button on layout in the graphical XML file editor Add the View.OnClickListener interface to the containing class's "implements" list if not there already. (Command+1 on Macs, Ctrl + 1 on PCs I believe). Use Eclipse to automatically add the code stub for unimplemented methods needed to support the View.OnClickListener interface, thus creating the event handler function stub. Find the stub and fill it in. However, if you have more than one possible click event source then you will need to inspect the View parameter to see which View element triggered the OnClick() event, thus requiring a case statement to handle multiple click event sources. NOTE: I am relatively new to Eclipse/Java so if there is a much easier way of doing this please let me know. Now that work flow isn't all that terrible, but again, that's just the simplest of use cases. Ratchet up the amount of extra work and thinking for a more complex component (aka widget) and the large number of properties/events it might have. It won't be long before you miss dearly the Delphi intelligent property editor and other designers. Eclipse tries to cover this ground by having an extensive list of properties in the menu that pops up when you right-click over a component/widget in the XML graphical layout editor. That's a huge and welcome assist but it's just not even close to the convenience of the Delphi IDE. Let me be very clear. I absolutely am not ranting nor do I want to start a Delphi vs. Java ideology discussion. Android/Eclipse/Java is what it is and there is a lot that impresses me. What I want to know is what other Delphi programmers that made the switch to the Eclipse/Java IDE have done to make things more Delphi like, and not just to make component/widget event code creation easier but any programming task. For example: Clever tips/tricks Eclipse plugins you found other ideas? Any great blog posts or web resources on the topic are appreciated too. -- roschler

    Read the article

  • Solaris 11

    - by user9154181
    Oracle has a strict policy about not discussing product features until they appear in shipping product. Now that Solaris 11 is publically available, it is time to catch up. I will be shortly posting articles on a variety of new developments in the Solaris linkers and related bits: 64-bit Archives After 40+ years of Unix, the archive file format has run out of room. The ar and link-editor (ld) commands have been enhanced to allow archives to grow past their previous 32-bit limits. Guidance The link-editor is now willing and able to tell you how to alter your link lines in order to build better objects. Stub Objects This is one of the bigger projects I've undertaken since joining the Solaris group. Stub objects are shared objects, built entirely from mapfiles, that supply the same linking interface as the real object, while containing no code or data. You can link to them, but cannot use them at runtime. It was pretty simple to add this ability to the link-editor, but the changes to the OSnet in order to apply them to building Solaris were massive. I discuss how we came to invent stub objects, how we apply them to build the OSnet in a more parallel and scalable manner, and about the follow on opportunities that have emerged from the new stub proto area we created to hold them. The elffile Utility A new standard Solaris utility, elffile is a variant of the file utility, focused exclusively on linker related files. elffile is of particular value for examining archives, as it allows you to find out what is inside them without having to first extract the archive members into temporary files. This release has been a long time coming. I joined the Solaris group in late 2005, and this will be my first FCS. From a user perspective, Solaris 11 is probably the biggest change to Solaris since Solaris 2.0. Solaris 11 polishes the ground breaking features from Solaris 10 (DTrace, FMA, ZFS, Zones), and uses them to add a powerful new packaging system, numerous other enhacements and features, along with a huge modernization effort. I'm excited to see it go out into the world. I hope you enjoy using it as much as we did creating it. Software is never done. On to the next one...

    Read the article

  • LazyInitializationException when adding to a list that is held within a entity class using hibernate

    - by molleman
    Right so i am working with hibernate gilead and gwt to persist my data on users and files of a website. my users have a list of file locations. i am using annotations to map my classes to the database. i am getting a org.hibernate.LazyInitializationException when i try to add file locations to the list that is held in the user class. this is a method below that is overridden from a external file upload servlet class that i am using. when the file uploads it calls this method. the user1 is loaded from the database elsewhere. the exception occurs at user1.getFileLocations().add(fileLocation); . i dont understand it really at all.! any help would be great. the stack trace of the error is below public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { for (FileItem item : sessionFiles) { if (false == item.isFormField()) { try { YFUser user1 = (YFUser)getSession().getAttribute(SESSION_USER); // This is the location where a file will be stored String fileLocationString = "/Users/Stefano/Desktop/UploadedFiles/" + user1.getUsername(); File fl = new File(fileLocationString); fl.mkdir(); // so here i will create the a file container for my uploaded file File file = File.createTempFile("upload-", ".bin",fl); // this is where the file is written to disk item.write(file); // the FileLocation object is then created FileLocation fileLocation = new FileLocation(); fileLocation.setLocation(fileLocationString); //test System.out.println("file path = "+file.getPath()); user1.getFileLocations().add(fileLocation); //the line above is where the exception occurs } catch (Exception e) { throw new UploadActionException(e.getMessage()); } } removeSessionFileItems(request); } return null; } //This is the class file for a Your Files User @Entity @Table(name = "yf_user_table") public class YFUser implements Serializable,ILightEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "user_id",nullable = false) private int userId; @Column(name = "username") private String username; @Column(name = "password") private String password; @Column(name = "email") private String email; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "USER_FILELOCATION", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "locationId") }) private List<FileLocation> fileLocations = new ArrayList<FileLocation>() ; public YFUser(){ } public int getUserId() { return userId; } private void setUserId(int userId) { this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public List<FileLocation> getFileLocations() { if(fileLocations ==null){ fileLocations = new ArrayList<FileLocation>(); } return fileLocations; } public void setFileLocations(List<FileLocation> fileLocations) { this.fileLocations = fileLocations; } /* public void addFileLocation(FileLocation location){ fileLocations.add(location); }*/ @Override public void addProxyInformation(String property, Object proxyInfo) { // TODO Auto-generated method stub } @Override public String getDebugString() { // TODO Auto-generated method stub return null; } @Override public Object getProxyInformation(String property) { // TODO Auto-generated method stub return null; } @Override public boolean isInitialized(String property) { // TODO Auto-generated method stub return false; } @Override public void removeProxyInformation(String property) { // TODO Auto-generated method stub } @Override public void setInitialized(String property, boolean initialised) { // TODO Auto-generated method stub } @Override public Object getValue() { // TODO Auto-generated method stub return null; } } @Entity @Table(name = "fileLocationTable") public class FileLocation implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "locationId", updatable = false, nullable = false) private int ieId; @Column (name = "location") private String location; public FileLocation(){ } public int getIeId() { return ieId; } private void setIeId(int ieId) { this.ieId = ieId; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } } Apr 2, 2010 11:33:12 PM org.hibernate.LazyInitializationException <init> SEVERE: failed to lazily initialize a collection of role: com.example.client.YFUser.fileLocations, no session or session was closed org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.client.YFUser.fileLocations, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:380) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:372) at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:365) at org.hibernate.collection.AbstractPersistentCollection.write(AbstractPersistentCollection.java:205) at org.hibernate.collection.PersistentBag.add(PersistentBag.java:297) at com.example.server.TestServiceImpl.saveFileLocation(TestServiceImpl.java:132) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at net.sf.gilead.gwt.PersistentRemoteService.processCall(PersistentRemoteService.java:174) at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:224) at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62) at javax.servlet.http.HttpServlet.service(HttpServlet.java:713) at javax.servlet.http.HttpServlet.service(HttpServlet.java:806) at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362) at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216) at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181) at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152) at org.mortbay.jetty.Server.handle(Server.java:324) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505) at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843) at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647) at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:211) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380) at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:396) at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488) Apr 2, 2010 11:33:12 PM net.sf.gilead.core.PersistentBeanManager clonePojo INFO: Third party instance, not cloned : org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.example.client.YFUser.fileLocations, no session or session was closed

    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

  • Java -Android. Parser problem

    - by Kano
    I am making a very simple app with an RSS reader. The reader works great, but it's only giving me the title, and i want the description too. I'am very new to android, and I have tried a lot of things, but I can't get it to work. I've found a lot of parsers but they are to complicated for me to understand, so I was hoping to find a simple solution, since it's only title and description i want. Can anyone help me? import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class NyhedActivity extends Activity { String streamTitle = ""; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.nyheder); TextView result = (TextView)findViewById(R.id.result); try { URL rssUrl = new URL("http://tv2sport.dk/rss/*/*/*/248/*/*"); SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance(); SAXParser mySAXParser = mySAXParserFactory.newSAXParser(); XMLReader myXMLReader = mySAXParser.getXMLReader(); RSSHandler myRSSHandler = new RSSHandler(); myXMLReader.setContentHandler(myRSSHandler); InputSource myInputSource = new InputSource(rssUrl.openStream()); myXMLReader.parse(myInputSource); result.setText(streamTitle); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); result.setText("Cannot connect RSS!"); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); result.setText("Cannot connect RSS!"); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); result.setText("Cannot connect RSS!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); result.setText("Cannot connect RSS!"); } } private class RSSHandler extends DefaultHandler { final int stateUnknown = 0; final int stateTitle = 1; int state = stateUnknown; int numberOfTitle = 0; String strTitle = ""; String strElement = ""; @Override public void startDocument() throws SAXException { // TODO Auto-generated method stub strTitle = "Nyheder fra "; } @Override public void endDocument() throws SAXException { // TODO Auto-generated method stub strTitle += ""; streamTitle = "" + strTitle; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { // TODO Auto-generated method stub if (localName.equalsIgnoreCase("title")) { state = stateTitle; strElement = ""; numberOfTitle++; } else { state = stateUnknown; } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // TODO Auto-generated method stub if (localName.equalsIgnoreCase("title")) { strTitle += strElement + "\n"+"\n"; } state = stateUnknown; } @Override public void characters(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub String strCharacters = new String(ch, start, length); if (state == stateTitle) { strElement += strCharacters; } } } }

    Read the article

  • How do I make a rectangle move in an image?

    - by alicedimarco
    Basically I have an image loaded, and when I click a portion of the image, a rectangle (with no fill) shows up. If I click another part of the image again, that rectangle will show up once more. With each click, the same rectangle should appear. So far I have this code, now I don't know how to make the image appear. My image from my file directory. I have already made the code to get the image from my file directory. import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class MP2 extends JPanel implements MouseListener{ JFrame frame; JPanel panel; int x = 0; int y = 0; String input; public MP2(){ } public static void main(String[] args){ JFrame frame = new JFrame(); MP2 panel = new MP2(); panel.addMouseListener(panel); frame.add(panel); frame.setSize(200,200); frame.setVisible(true); } public void mouseClicked(MouseEvent event) { // TODO Auto-generated method stub this.x = event.getX(); this.y = event.getY(); this.repaint(); input = JOptionPane.showInputDialog("Something pops out"); System.out.println(input); } public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } public void paintComponent(Graphics g){ super.paintComponent(g); // this.setBackground(Color.white); *Sets the bg color of the panel g.setColor(new Color(255,0,0)); g.drawRect(x, y, 100, 100); } }

    Read the article

  • Any suggestions for improvement on this style for BDD/TDD?

    - by Sean B
    I was tinkering with doing the setups with our unit test specifciations which go like Specification for SUT when behaviour X happens in scenario Y Given that this thing And also this other thing When I do X... Then It should do ... And It should also do ... I wrapped each of the steps of the GivenThat in Actions... any feed back whether separating with Actions is good / bad / or better way to make the GivenThat clear? /// <summary> /// Given a product is setup for injection /// And Product Image Factory Is Stubbed(); /// And Product Size Is Stubbed(); /// And Drawing Scale Is Stubbed(); /// And Product Type Is Stubbed(); /// </summary> protected override void GivenThat() { base.GivenThat(); Action givenThatAProductIsSetupforInjection = () => { var randomGenerator = new RandomGenerator(); this.Position = randomGenerator.Generate<Point>(); this.Product = new Diffuser { Size = new RectangularProductSize( 2.Inches()), Position = this.Position, ProductType = Dep<IProductType>() }; }; Action andProductImageFactoryIsStubbed = () => Dep<IProductBitmapImageFactory>().Stub(f => f.GetInstance(Dep<IProductType>())).Return(ExpectedBitmapImage); Action andProductSizeIsStubbed = () => { Stub<IDisplacementProduct, IProductSize>(p => p.Size); var productBounds = new ProductBounds(Width.Feet(), Height.Feet()); Dep<IProductSize>().Stub(s => s.Bounds).Return(productBounds); }; Action andDrawingScaleIsStubbed = () => Dep<IDrawingScale>().Stub(s => s.PixelsPerFoot).Return(PixelsPerFoot); Action andProductTypeIsStubbed = () => Stub<IDisplacementProduct, IProductType>(p => p.ProductType); givenThatAProductIsSetupforInjection(); andProductImageFactoryIsStubbed(); andProductSizeIsStubbed(); andDrawingScaleIsStubbed(); andProductTypeIsStubbed(); }

    Read the article

  • Using Lambdas for return values in Rhino.Mocks

    - by PSteele
    In a recent StackOverflow question, someone showed some sample code they’d like to be able to use.  The particular syntax they used isn’t supported by Rhino.Mocks, but it was an interesting idea that I thought could be easily implemented with an extension method. Background When stubbing a method return value, Rhino.Mocks supports the following syntax: dependency.Stub(s => s.GetSomething()).Return(new Order()); The method signature is generic and therefore you get compile-time type checking that the object you’re returning matches the return value defined by the “GetSomething” method. You could also have Rhino.Mocks execute arbitrary code using the “Do” method: dependency.Stub(s => s.GetSomething()).Do((Func<Order>) (() => new Order())); This requires the cast though.  It works, but isn’t as clean as the original poster wanted.  They showed a simple example of something they’d like to see: dependency.Stub(s => s.GetSomething()).Return(() => new Order()); Very clean, simple and no casting required.  While Rhino.Mocks doesn’t support this syntax, it’s easy to add it via an extension method. The Rhino.Mocks “Stub” method returns an IMethodOptions<T>.  We just need to accept a Func<T> and use that as the return value.  At first, this would seem straightforward: public static IMethodOptions<T> Return<T>(this IMethodOptions<T> opts, Func<T> factory) { opts.Return(factory()); return opts; } And this would work and would provide the syntax the user was looking for.  But the problem with this is that you loose the late-bound semantics of a lambda.  The Func<T> is executed immediately and stored as the return value.  At the point you’re setting up your mocks and stubs (the “Arrange” part of “Arrange, Act, Assert”), you may not want the lambda executing – you probably want it delayed until the method is actually executed and Rhino.Mocks plugs in your return value. So let’s make a few small tweaks: public static IMethodOptions<T> Return<T>(this IMethodOptions<T> opts, Func<T> factory) { opts.Return(default(T)); // required for Rhino.Mocks on non-void methods opts.WhenCalled(mi => mi.ReturnValue = factory()); return opts; } As you can see, we still need to set up some kind of return value or Rhino.Mocks will complain as soon as it intercepts a call to our stubbed method.  We use the “WhenCalled” method to set the return value equal to the execution of our lambda.  This gives us the delayed execution we’re looking for and a nice syntax for lambda-based return values in Rhino.Mocks. Technorati Tags: .NET,Rhino.Mocks,Mocking,Extension Methods

    Read the article

  • How do I get my character to move after adding to JFrame?

    - by A.K.
    So this is kind of a follow up on my other JPanel question that got resolved by playing around with the Layout... Now my MouseListener allows me to add a new Board(); object from its class, which is the actual game map and animator itself. But since my Board() takes Key Events from a Player Object inside the Board Class, I'm not sure if they are being started. Here's my Frame Class, where SideScroller S is the player object: package OurPackage; //Made By A.K. 5/24/12 //Contains Frame. import java.awt.BorderLayout; import java.awt.Button; import java.awt.CardLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.*; import javax.swing.plaf.basic.BasicOptionPaneUI.ButtonActionListener; public class Frame implements MouseListener { public static boolean StartGame = false; JFrame frm = new JFrame("Action-Packed Jack"); ImageIcon img = new ImageIcon(getClass().getResource("/Images/ActionJackTitle.png")); ImageIcon StartImg = new ImageIcon(getClass().getResource("/Images/JackStart.png")); public Image Title; JLabel TitleL = new JLabel(img); public JPanel TitlePane = new JPanel(); public JPanel BoardPane = new JPanel(); JPanel cards; JButton StartB = new JButton(StartImg); Board nBoard = new Board(); static Sound nSound; public Frame() { frm.setLayout(new GridBagLayout()); cards = new JPanel(new CardLayout()); nSound = new Sound("/Sounds/BunchaJazz.wav"); TitleL.setPreferredSize(new Dimension(970, 420)); frm.add(TitleL); frm.add(cards); cards.setSize(new Dimension(150, 45)); cards.setLayout(new GridBagLayout ()); cards.add(StartB); StartB.addMouseListener(this); StartB.setPreferredSize(new Dimension(150, 45)); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setSize(1200, 420); frm.setVisible(true); frm.setResizable(false); frm.setLocationRelativeTo(null); frm.pack(); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new Frame(); } }); } public void mouseClicked(MouseEvent e) { nSound.play(); StartB.setContentAreaFilled(false); cards.remove(StartB); frm.remove(TitleL); frm.remove(cards); frm.setLayout(new GridLayout(1, 1)); frm.add(nBoard); //Add Game "Tiles" Or Content. x = 1200 nBoard.setPreferredSize(new Dimension(1200, 420)); cards.revalidate(); frm.validate(); } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }

    Read the article

  • Can't remove JPanel from JFrame while adding new class into it

    - by A.K.
    Basically, I have my Frame class, which instantiates all the properties for the JFrame, and draws a JLabel with an image (my title screen). Then I made a separate JPanel with a start button on it, and made a mouse listener that will allow me to remove these objects while adding in a new Board() class (Which paints the main game). *Note: The JLabel is SEPARATE from the JPanel, but it still gets moved to the side by it. Problem: Whenever I click the button though, it only shows a little square of what I presume is my board class trying to run. Code below for the Frame Class: package OurPackage; //Made By A.K. 5/24/12 //Contains Frame. import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Image; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.*; import javax.swing.plaf.basic.BasicOptionPaneUI.ButtonActionListener; public class Frame implements MouseListener { public static boolean StartGame = false; ImageIcon img = new ImageIcon(getClass().getResource("/Images/ActionJackTitle.png")); ImageIcon StartImg = new ImageIcon(getClass().getResource("/Images/JackStart.png")); public Image Title; JLabel TitleL = new JLabel(img); public JPanel panel = new JPanel(); JButton StartB = new JButton(StartImg); JFrame frm = new JFrame("Action-Packed Jack"); public Frame() { TitleL.setPreferredSize(new Dimension(1200, 420)); frm.add(TitleL); frm.setLayout(new GridBagLayout()); frm.add(panel); panel.setSize(new Dimension(220, 45)); panel.setLayout(new GridBagLayout ()); panel.add(StartB); StartB.addMouseListener(this); StartB.setPreferredSize(new Dimension(220, 45)); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frm.setSize(1200, 420); frm.setVisible(true); frm.setResizable(false); frm.setLocationRelativeTo(null); } public static void main(String[] args) { new Frame(); } public void mouseClicked(MouseEvent e) { StartB.setContentAreaFilled(false); panel.remove(StartB); frm.remove(panel); frm.remove(TitleL); //frm.setLayout(null); frm.add(new Board()); //Add Game "Tiles" Or Content. x = 1200 frm.validate(); System.out.println("Hit!"); } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }

    Read the article

  • Implementing a customized drawable in Android

    - by Girish
    Hi , I was trying to get hold of 2D graphics in Android. As a example i want to implement a custom drawable and show it in my Activity I have defined a customized drawable by extending from Android drawable as mentioned below myDrawable extends Drawable { private static final String TAG = myDrawable.class.getSimpleName(); private ColorFilter cf; @Override public void draw(Canvas canvas) { //First you define a colour for the outline of your rectangle Paint rectanglePaint = new Paint(); rectanglePaint.setARGB(255, 255, 0, 0); rectanglePaint.setStrokeWidth(2); rectanglePaint.setStyle(Style.FILL); //Then create yourself a Rectangle RectF rectangle = new RectF(15.0f, 50.0f, 55.0f, 75.0f); //in pixels Log.d(TAG,"On Draw method"); // TODO Auto-generated method stub Paint paintHandl = new Paint(); // paintHandl.setColor(0xaabbcc); paintHandl.setARGB(125, 234, 213, 34 ); RectF rectObj = new RectF(5,5,25,25); canvas.drawRoundRect(rectangle, 0.5f, 0.5f, rectanglePaint); } @Override public int getOpacity() { // TODO Auto-generated method stub return 100; } @Override public void setAlpha(int alpha) { // TODO Auto-generated method stub } @Override public void setColorFilter(ColorFilter cf) { // TODO Auto-generated method stub this.cf = cf; } } I am trying to get this displayed in my activity, as shown below public class custDrawable extends Activity { /** Called when the activity is first created. */ LinearLayout layObj = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); layObj = (LinearLayout) findViewById(R.id.parentLay); ImageView imageView = (ImageView) findViewById(R.id.icon2); myDrawable myDrawObj = new myDrawable(); imageView.setImageDrawable(myDrawObj); imageView.invalidate(); // layObj.addView(myDrawObj, params); } } But when i run the app i see no rectangle on the activity, can anyone help me out? Where am i going wrong?

    Read the article

  • NoSuchMethodError: com/sun/istack/logging/Logger.getLogger

    - by pandi-sus
    I developed a webservice and deployed it to websphere 7.0 and developed a dynamic dispatch client using JAX-WS APIs which also runs on same application server. I get error at the following line: Dispatch dispatch = service.createDispatch(portName, SOAPMessage.class, Service.Mode.MESSAGE); Error: Caused by: java.lang.NoSuchMethodError: com/sun/istack/logging/Logger.getLogger(Ljava/lang/Class;)Lcom/sun/istack/logging/Logger; at com.sun.xml.ws.api.config.management.policy.ManagementAssertion.(ManagementAssertion.java:87) at java.lang.J9VMInternals.initializeImpl(Native Method) at java.lang.J9VMInternals.initialize(J9VMInternals.java:200) at java.lang.J9VMInternals.initialize(J9VMInternals.java:167) at com.sun.xml.ws.server.MonitorBase.createManagedObjectManager(MonitorBase.java:177) at com.sun.xml.ws.client.Stub.(Stub.java:196) at com.sun.xml.ws.client.Stub.(Stub.java:174) at com.sun.xml.ws.client.dispatch.DispatchImpl.(DispatchImpl.java:129) at com.sun.xml.ws.client.dispatch.SOAPMessageDispatch.(SOAPMessageDispatch.java:77) at com.sun.xml.ws.api.pipe.Stubs.createSAAJDispatch(Stubs.java:143) at com.sun.xml.ws.api.pipe.Stubs.createDispatch(Stubs.java:264) at com.sun.xml.ws.client.WSServiceDelegate.createDispatch(WSServiceDelegate.java:390) at com.sun.xml.ws.client.WSServiceDelegate.createDispatch(WSServiceDelegate.java:401) at com.sun.xml.ws.client.WSServiceDelegate.createDispatch(WSServiceDelegate.java:383) at javax.xml.ws.Service.createDispatch(Service.java:336) I included the following dependency. javax.xml.ws jaxws-api 2.1 I also tried adding policy dependency (versions - 2.2 and 2.2.1) com.sun.xml.ws policy 2.2.1 Any ideas on what more dependencies I need to add?

    Read the article

  • Getting GPS data?

    - by svebee
    Inside public class IAmHere extends Activity implements LocationListener { i have @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } and inside public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.iamhere); i have LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); List<String> providers = lm.getProviders(true); /* Loop over the array backwards, and if you get an accurate location, then break out the loop*/ Location l = null; for (int i=providers.size()-1; i>=0; i--) { l = lm.getLastKnownLocation(providers.get(i)); if (l != null) break; } double[] gps = new double[2]; if (l != null) { gps[0] = l.getLatitude(); gps[1] = l.getLongitude(); } gpsString = (TextView)findViewById(R.id.gpsString); String Data = ""; String koordinata1 = Double.toString(gps[0]); String koordinata2 = Double.toString(gps[1]); Data = Data + koordinata1 + " | " + koordinata2 + "\n"; gpsString.setText(String.valueOf(Data)); but seems it's not working? Why? I mean even emulator doesn't want to send GPS data - When I click "send" via UI or console, nothing happens...? Thank you.

    Read the article

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