Search Results

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

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

  • how to create class alert using lcdui package in blackberry

    - by Baby
    Advance Thanks.i am new to blackberry developement.i try the following code for creating alert using lcdui package.but nothing will coming when i am running Plz help me. package alertpack; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.AlertType; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.Screen; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; import net.rim.device.api.ui.Color; import net.rim.device.api.ui.Graphics; public class alertclass extends MIDlet implements CommandListener { private Display display; private Alert alert; private Form form = new Form("Throw Exception"); private Command exit = new Command("Exit", Command.SCREEN, 1); //public static void main(String[] args) //{ //} private boolean exitFlag = false; public alertclass(){ display = Display.getDisplay(this); form.addCommand(exit); form.setCommandListener(this); } protected void destroyApp(boolean unconditional) throws MIDletStateChangeException { // TODO Auto-generated method stub if (unconditional == false) { throw new MIDletStateChangeException(); } } protected void pauseApp() { // TODO Auto-generated method stub } protected void startApp() throws MIDletStateChangeException { // TODO Auto-generated method stub display.setCurrent(form); } public void commandAction(Command c, Displayable d) { // TODO Auto-generated method stub if (c == exit) { try { if (exitFlag == false) { alert = new Alert("Busy", "Please try again.", null, AlertType.WARNING); alert.setTimeout(Alert.FOREVER); display.setCurrent(alert, form); destroyApp(false); } else { destroyApp(true); notifyDestroyed(); } } catch (Exception exception) { exitFlag = true; } } } }

    Read the article

  • Repaint() not calling paint() in Java

    - by Joshua Auriemma
    Let me start off by saying I know I've violated some basic Java principles in this messy code, but I'm desperately trying to finish a program by Tuesday for a social science experiment, and I don't know Java, so I'm basically just fumbling through it for now. With that disclaimer out of the way, I have a separate program working where a circle is moving around the screen and the user must click on it. It works fine when its in its own separate class file, but when I add the code to my main program, it's no longer working. I don't even really understand why repaint() calls my paint() function — as far as I'm concerned, it's magic, but I've noticed that repaint() calls paint() in my test program, but not in the more complicated actual program, and I assume that's why the circle is no longer painting on my program. Entire code is below: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.*; import java.awt.event.*; import java.awt.geom.Ellipse2D; import java.io.FileReader; import java.io.IOException; import java.util.Calendar; public class Reflexology1 extends JFrame{ private static final long serialVersionUID = -1295261024563143679L; private Ellipse2D ball = new Ellipse2D.Double(0, 0, 25, 25); private Timer moveBallTimer; int _ballXpos, _ballYpos; JButton button1, button2; JButton movingButton; JTextArea textArea1; int buttonAClicked, buttonDClicked; private long _openTime = 0; private long _closeTime = 0; JPanel thePanel = new JPanel(); JPanel thePlacebo = new JPanel(); final JFrame frame = new JFrame("Reflexology"); final JFrame frame2 = new JFrame("The Test"); JLabel label1 = new JLabel("Press X and then click the moving dot as fast as you can."); public static void main(String[] args){ new Reflexology1(); } public Reflexology1(){ frame.setSize(600, 475); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("Reflexology 1.0"); frame.setResizable(false); frame2.setSize(600, 475); frame2.setLocationRelativeTo(null); frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame2.setTitle("Reflexology 1.0"); frame2.setResizable(false); button1 = new JButton("Accept"); button2 = new JButton("Decline"); //movingButton = new JButton("Click Me"); ListenForAcceptButton lForAButton = new ListenForAcceptButton(); ListenForDeclineButton lForDButton = new ListenForDeclineButton(); button1.addActionListener(lForAButton); button2.addActionListener(lForDButton); //movingButton.addActionListener(lForMButton); JTextArea textArea1 = new JTextArea(24, 50); textArea1.setText("Tracking Events\n"); textArea1.setLineWrap(true); textArea1.setWrapStyleWord(true); textArea1.setSize(15, 50); textArea1.setEditable(false); FileReader reader = null; try { reader = new FileReader("EULA.txt"); textArea1.read(reader, "EULA.txt"); } catch (IOException exception) { System.err.println("Problem loading file"); exception.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException exception) { System.err.println("Error closing reader"); exception.printStackTrace(); } } } JScrollPane scrollBar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); AdjustmentListener listener = new MyAdjustmentListener(); thePanel.add(scrollBar1); thePanel.add(button1); thePanel.add(button2); frame.add(thePanel); ListenForMouse lForMouse = new ListenForMouse(); thePlacebo.addMouseListener(lForMouse); thePlacebo.add(label1); frame2.add(thePlacebo); ListenForWindow lForWindow = new ListenForWindow(); frame.addWindowListener(lForWindow); frame2.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e){ if(e.getKeyChar() == 'X' || e.getKeyChar() == 'x') {moveBallTimer.start();} } }); frame.setVisible(true); moveBallTimer = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent e) { moveBall(); System.out.println("Timer started!"); repaint(); } }); addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if(frame2.isVisible()){ moveBallTimer.start(); } } }); } private class ListenForAcceptButton implements ActionListener{ public void actionPerformed(ActionEvent e){ if (e.getSource() == button1){ Calendar ClCDateTime = Calendar.getInstance(); System.out.println(ClCDateTime.getTimeInMillis() - _openTime); _closeTime = ClCDateTime.getTimeInMillis() - _openTime; //frame.getContentPane().remove(thePanel); //thePlacebo.addKeyListener(lForKeys); //frame.getContentPane().add(thePlacebo); //frame.repaint(); //moveBallTimer.start(); frame.setVisible(false); frame2.setVisible(true); frame2.revalidate(); frame2.repaint(); } } } private class ListenForDeclineButton implements ActionListener{ public void actionPerformed(ActionEvent e){ if (e.getSource() == button2){ JOptionPane.showMessageDialog(Reflexology1.this, "You've declined the license agreement. DO NOT RESTART the program. Please go inform a researcher that you have declined the agreement.", "WARNING", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } } private class ListenForWindow implements WindowListener{ public void windowActivated(WindowEvent e) { //textArea1.append("Window is active"); } // if this.dispose() is called, this is called: public void windowClosed(WindowEvent arg0) { } // When a window is closed from a menu, this is called: public void windowClosing(WindowEvent arg0) { } // Called when the window is no longer the active window: public void windowDeactivated(WindowEvent arg0) { //textArea1.append("Window is NOT active"); } // Window gone from minimized to normal state public void windowDeiconified(WindowEvent arg0) { //textArea1.append("Window is in normal state"); } // Window has been minimized public void windowIconified(WindowEvent arg0) { //textArea1.append("Window is minimized"); } // Called when the Window is originally created public void windowOpened(WindowEvent arg0) { //textArea1.append("Let there be Window!"); Calendar OlCDateTime = Calendar.getInstance(); _openTime = OlCDateTime.getTimeInMillis(); //System.out.println(_openTime); } } private class MyAdjustmentListener implements AdjustmentListener { public void adjustmentValueChanged(AdjustmentEvent arg0) { AdjustmentEvent scrollBar1; //System.out.println(scrollBar1.getValue())); } } public void paint(Graphics g) { //super.paint(g); frame2.paint(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.RED); g2d.fill(ball); System.out.println("Calling fill()"); } protected void moveBall() { //System.out.println("I'm in the moveBall() function!"); int width = getWidth(); int height = getHeight(); int min, max, randomX, randomY; min =200; max = -200; randomX = min + (int)(Math.random() * ((max - min)+1)); randomY = min + (int)(Math.random() * ((max - min)+1)); //System.out.println(randomX + ", " + randomY); Rectangle ballBounds = ball.getBounds(); //System.out.println(ballBounds.x + ", " + ballBounds.y); if (ballBounds.x + randomX < 0) { randomX = 200; } else if (ballBounds.x + ballBounds.width + randomX > width) { randomX = -200; } if (ballBounds.y + randomY < 0) { randomY = 200; } else if (ballBounds.y + ballBounds.height + randomY > height) { randomY = -200; } ballBounds.x += randomX; ballBounds.y += randomY; _ballXpos = ballBounds.x; _ballYpos = ballBounds.y; ball.setFrame(ballBounds); } public void start() { moveBallTimer.start(); } public void stop() { moveBallTimer.stop(); } private class ListenForMouse implements MouseListener{ // Called when the mouse is clicked public void mouseClicked(MouseEvent e) { //System.out.println("Mouse Panel pos: " + e.getX() + " " + e.getY() + "\n"); if (e.getX() >=_ballXpos && e.getX() <= _ballXpos + 25 && e.getY() <=_ballYpos && e.getY() >= _ballYpos - 25 ) { System.out.println("TRUE"); } System.out.println("{e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos + " | " + "{e.getY(): " + e.getY() + " / " + "_ballYpos: " + _ballYpos); } 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 } } // System.out.println("e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos); // Mouse over public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } // Mouse left the mouseover area: 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 } } Could anyone tell me what I need to do to get repaint() to call the paint() method in the above program? I'm assuming the multiple frames is causing the problem, but that's just a guess. Thanks.

    Read the article

  • Why null reference exception in SetMolePublicInstance?

    - by OldGrantonian
    I get a "null reference" exception in the following line: MoleRuntime.SetMolePublicInstance(stub, receiverType, objReceiver, name, null); The program builds and compiles correctly. There are no complaints about any of the parameters to the method. Here's the specification of SetMolePublicInstance, from the object browser: SetMolePublicInstance(System.Delegate _stub, System.Type receiverType, object _receiver, string name, params System.Type[] parameterTypes) Here are the parameter values for "Locals": + stub {Method = {System.String <StaticMethodUnitTestWithDeq>b__0()}} System.Func<string> + receiverType {Name = "OrigValue" FullName = "OrigValueP.OrigValue"} System.Type {System.RuntimeType} objReceiver {OrigValueP.OrigValue} object {OrigValueP.OrigValue} name "TestString" string parameterTypes null object[] I know that TestString() takes no parameters and returns string, so as a starter to try to get things working, I specified "null" for the final parameter to SetMolePublicInstance. As already mentioned, this compiles OK. Here's the stack trace: Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.ExtendedReflection.Collections.Indexable.ConvertAllToArray[TInput,TOutput](TInput[] array, Converter`2 converter) at Microsoft.Moles.Framework.Moles.MoleRuntime.SetMole(Delegate _stub, Type receiverType, Object _receiver, String name, MoleBindingFlags flags, Type[] parameterTypes) at Microsoft.Moles.Framework.Moles.MoleRuntime.SetMolePublicInstance(Delegate _stub, Type receiverType, Object _receiver, String name, Type[] parameterTypes) at DeqP.Deq.Replace[T](Func`1 stub, Type receiverType, Object objReceiver, String name) in C:\0VisProjects\DecP_04\DecP\DeqC.cs:line 38 at DeqPTest.DecCTest.StaticMethodUnitTestWithDeq() in C:\0VisProjects\DecP_04\DecPTest\DeqCTest.cs:line 28 at Starter.Start.Main(String[] args) in C:\0VisProjects\DecP_04\Starter\Starter.cs:line 14 Press any key to continue . . . To avoid the null parameter, I changed the final "null" to "parameterTypes" as in the following line: MoleRuntime.SetMolePublicInstance(stub, receiverType, objReceiver, name, parameterTypes); I then tried each of the following (before the line): int[] parameterTypes = null; // if this is null, I don't think the type will matter int[] parameterTypes = new int[0]; object[] parameterTypes = new object[0]; // this would allow for various parameter types All three attempts produce a red squiggly line under the entire line for SetMolePublicInstance Mouseover showed the following message: The best overloaded method match for 'Microsoft.Moles.Framework.Moles.MoleRuntime.SetMolePublicInstance(System.Delegate, System.Type, object, string, params System.Type[])' has some invalid arguments. I'm assuming that the first four arguments are OK, and that the problem is with the params array.

    Read the article

  • retrieving and restoring textview information from sharedpreferences

    - by user1742524
    I have an activity that allows user to enter notes and store them in dynamically created textviews. However, when the use leaves the activity and returns, all the created textviews disappear. How can i store store or retrieve all of these created textviews, whenever i return to the activity? Also, i think that my sharedpreferences will be overwriting each time a new textview is added. Any suggestions? public class DocNoteActivity extends Activity { private LinearLayout nLayout; private EditText etDocNote; private Button btnAdd1; public static final String PREFS_NAME = "MyPrefsFile"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.adddocnote); etDocNote = (EditText) findViewById(R.id.editDocNote); btnAdd1 = (Button) findViewById(R.id.btnAdd1); nLayout = (LinearLayout) findViewById(R.id.linearLayout); TextView tvNote = new TextView(this); tvNote.setText(""); btnAdd1.setOnClickListener(onClick()); } private OnClickListener onClick() { // TODO Auto-generated method stub return new OnClickListener(){ public void onClick(View v) { // TODO Auto-generated method stub String newDocNote = etDocNote.getText().toString(); nLayout.addView(createNewTextView(newDocNote)); getSharedPreferences("myprefs", 0).edit().putString("etDocNote", newDocNote).commit(); } }; } private TextView createNewTextView(String newText) { // TODO Auto-generated method stub LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); TextView tvNote = new TextView(this); tvNote.setLayoutParams(lparams); tvNote.setText(newText); return tvNote; } }

    Read the article

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

    - 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; /* private List uploadedUsers = new ArrayList(); */ 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; } /* public List getUploadedUsers() { return uploadedUsers; } public void setUploadedUsers(List<YFUser> uploadedUsers) { this.uploadedUsers = uploadedUsers; } public void addUploadedUser(YFUser user){ uploadedUsers.add(user); } */ } 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

  • Trouble with RSpec's with method

    - by Thiago
    Hi there, I've coded the following spec: it "should call user.invite_friend" do user = mock_model(User, :id = 1) other_user = mock_model(User, :id = 2) User.stub!(:find).with(user.id).and_return(user) User.stub!(:find).with(other_user.id).and_return(other_user) user.should_receive(:invite_friend).with(other_user) post :invite, { :id = other_user.id }, {:user_id = user.id} end But I'm getting the following error when I run the specs NoMethodError in 'UsersController POST invite should call user.invite_friend' undefined method `find' for # Class:0x86d6918 app/controllers/users_controller.rb:144:in `invite' ./spec/controllers/users_controller_spec.rb:13: What's the mistake? Without .with it works just fine, but I want different return values for different arguments to the stub method. The following controller's actions might be relevant: def invite me.invite_friend(User.find params[:id]) respond_to do |format| format.html { redirect_to user_path(params[:id]) } end end def me User.find(session[:user_id]) end

    Read the article

  • Android draw using SurfaceView and Thread

    - by Morten Høgseth
    I am trying to draw a ball to my screen using 3 classes. I have read a little about this and I found a code snippet that works using the 3 classes on one page, Playing with graphics in Android I altered the code so that I have a ball that is moving and shifts direction when hitting the wall like the picture below (this is using the code in the link). Now I like to separate the classes into 3 different pages for not making everything so crowded, everything is set up the same way. Here are the 3 classes I have. BallActivity.java Ball.java BallThread.java package com.brick.breaker; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class BallActivity extends Activity { private Ball ball; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); ball = new Ball(this); setContentView(ball); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); setContentView(null); ball = null; finish(); } } package com.brick.breaker; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.view.SurfaceHolder; import android.view.SurfaceView; public class Ball extends SurfaceView implements SurfaceHolder.Callback { private BallThread ballThread = null; private Bitmap bitmap; private float x, y; private float vx, vy; public Ball(Context context) { super(context); // TODO Auto-generated constructor stub bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ball); x = 50.0f; y = 50.0f; vx = 10.0f; vy = 10.0f; getHolder().addCallback(this); ballThread = new BallThread(getHolder(), this); } protected void onDraw(Canvas canvas) { update(canvas); canvas.drawBitmap(bitmap, x, y, null); } public void update(Canvas canvas) { checkCollisions(canvas); x += vx; y += vy; } public void checkCollisions(Canvas canvas) { if(x - vx < 0) { vx = Math.abs(vx); } else if(x + vx > canvas.getWidth() - getBitmapWidth()) { vx = -Math.abs(vx); } if(y - vy < 0) { vy = Math.abs(vy); } else if(y + vy > canvas.getHeight() - getBitmapHeight()) { vy = -Math.abs(vy); } } public int getBitmapWidth() { if(bitmap != null) { return bitmap.getWidth(); } else { return 0; } } public int getBitmapHeight() { if(bitmap != null) { return bitmap.getHeight(); } else { return 0; } } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub ballThread.setRunnable(true); ballThread.start(); } public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub boolean retry = true; ballThread.setRunnable(false); while(retry) { try { ballThread.join(); retry = false; } catch(InterruptedException ie) { //Try again and again and again } break; } ballThread = null; } } package com.brick.breaker; import android.graphics.Canvas; import android.view.SurfaceHolder; public class BallThread extends Thread { private SurfaceHolder sh; private Ball ball; private Canvas canvas; private boolean run = false; public BallThread(SurfaceHolder _holder,Ball _ball) { sh = _holder; ball = _ball; } public void setRunnable(boolean _run) { run = _run; } public void run() { while(run) { canvas = null; try { canvas = sh.lockCanvas(null); synchronized(sh) { ball.onDraw(canvas); } } finally { if(canvas != null) { sh.unlockCanvasAndPost(canvas); } } } } public Canvas getCanvas() { if(canvas != null) { return canvas; } else { return null; } } } Here is a picture that shows the outcome of these classes. I've tried to figure this out but since I am pretty new to Android development I thought I could ask for help. Does any one know what is causing the ball to be draw like that? The code is pretty much the same as the one in the link and I have tried to experiment to find a solution but no luck. Thx in advance for any help=)

    Read the article

  • Android EditText and addTextChangedListener

    - by Alex
    im currently porting a database manager to android and due to performance reasons i like to update only propertys that have been modified. Im trying to do this with the addTextChangedListener in order to add modified entrys to a List, but my Program never enters any of its methods. EditText Et = (EditText) Editors.get(Prop.Name); Et.addTextChangedListener(new TextWatcher() { @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub if(Prop.GetType() == Property.PROPTYPE.num) { float f = Float.parseFloat(s.toString()); Prop.FromString(f); } else { Prop.FromString(s.toString()); } propertiesToUpdate.add(Prop); }); Et.setText(Prop.ToString());

    Read the article

  • Need help mocking a ASP.NET Controller in Rhino Mocks

    - by Pure.Krome
    Hi folks, I'm trying to mock up a fake ASP.NET Controller. I don't have any concrete controllers, so I was hoping to just mock a Controller and it will work. This is what I currently have: _fakeRequestBase = MockRepository.GenerateMock<HttpRequestBase>(); _fakeRequestBase.Stub(x => x.HttpMethod).Return("GET"); _fakeContextBase = MockRepository.GenerateMock<HttpContextBase>(); _fakeContextBase.Stub(x => x.Request).Return(_fakeRequestBase); var controllerContext = new ControllerContext(_fakeContextBase, new RouteData(), MockRepository.GenerateMock<ControllerBase>()); _fakeController = MockRepository.GenerateMock<Controller>(); _fakeController.Stub(x => x.ControllerContext).Return(controllerContext); Everything works except the last line, which throws a runtime error and is asking me for some Rhino.Mocks source code or something (which I don't have). See how I'm trying to mock up an abstract Controller - is that allowed? Can someone help me?

    Read the article

  • What is the best way to mock a 3rd party object in ruby?

    - by spinlock
    I'm writing a test app using the twitter gem and I'd like to write an integration test but I can't figure out how to mock the objects in the Twitter namespace. Here's the function that I want to test: def build_twitter(omniauth) Twitter.configure do |config| config.consumer_key = TWITTER_KEY config.consumer_secret = TWITTER_SECRET config.oauth_token = omniauth['credentials']['token'] config.oauth_token_secret = omniauth['credentials']['secret'] end client = Twitter::Client.new user = client.current_user self.name = user.name end and here's the rspec test that I'm trying to write: feature 'testing oauth' do before(:each) do @twitter = double("Twitter") @twitter.stub!(:configure).and_return true @client = double("Twitter::Client") @client.stub!(:current_user).and_return(@user) @user = double("Twitter::User") @user.stub!(:name).and_return("Tester") end scenario 'twitter' do visit root_path login_with_oauth page.should have_content("Pages#home") end end But, I'm getting this error: 1) testing oauth twitter Failure/Error: login_with_oauth Twitter::Error::Unauthorized: GET https://api.twitter.com/1/account/verify_credentials.json: 401: Invalid / expired Token # ./app/models/user.rb:40:in `build_twitter' # ./app/models/user.rb:16:in `build_authentication' # ./app/controllers/authentications_controller.rb:47:in `create' # ./spec/support/integration_spec_helper.rb:3:in `login_with_oauth' # ./spec/integration/twit_test.rb:16:in `block (2 levels) in <top (required)>' The mocks above are using rspec but I'm open to trying mocha too. Any help would be greatly appreciated.

    Read the article

  • Examine one particular call and ignore the rest

    - by lulalala
    I have a Currency class and want to update its rates. The following is the spec of an update class I plan to write: describe WebCrawlers::Currency::FeedParser do let(:gbp){ double('GBP').as_null_object } let(:usd){ double('USD').as_null_object } describe '#perform' do before do Currency.stub(:find_by_name).with('GBP').and_return( gbp ) Currency.stub(:find_by_name).with('USD').and_return( usd ) end it 'should update GBP rate' do gbp.should_receive(:update_attributes).with(rate_to_usd:0.63114) subject.perform end it 'should not update USD rate' do usd.should_not_receive(:update_attributes) subject.perform end end end and it works find if I only update GBP in my actual class: class WebCrawlers::Currency::FeedParser def perform Currency.find_by_name('GBP').update_attributes(rate_to_usd: 0.63114) end end However once I start updating other currencies like 'CAD', Rspec complains <Currency> received :find_by_name with unexpected arguments expected: ("USD") got: ("CAD") Why is this the case? Instead of NOT expecting USD, it says it is. And in the future there will be lots of currencies to update, but I don't want to test and stub each one of them. How can I resolve this issue?

    Read the article

  • Flex 1009 error Chart datatip

    - by JMcNally
    I am simply trying to hide a datatip on a chart if the hit data item (yfield item) is == 101 for two differnt series an areaseries and a line series. The following funciton works in IE but throws an error in firefox. I am new to flex and was wondering if there is a better way to approch this.. the code in // is causing the error. public function datatip_M_chart(e:HitData):String { //if (e.item.STUB == 101) {e.chartItem.itemRenderer.alpha = 0}// if (e.chartItem is AreaSeriesItem){ return'<b>'+COMBO.selectedLabel+'</b>'+ '<br/><i>Age: </i>' + e.item.STUB + '<br/><i>Percentage:</i> ' + e.item.M_PROP+'%'; }else{ return'<b>'+COMBO2.selectedLabel+'</b>'+ '<br/><i>Age: </i>' + e.item.STUB + '<br/><i>Percentage:</i> ' + e.item.M_PROP+'%'; }

    Read the article

  • How to close reconnect SocketIOClient on android?

    - by erginduran
    My problem is reconnect.I connect SocketIOClient.connect(..) in background service.I close service when internet connection is off.and I re-start service again connection on. How to close this reconnection?I don't want to reconnect SocketIOClient. Its my code: ConnectCallback mConnectCallback = new ConnectCallback() { @Override public void onConnectCompleted(Exception ex, SocketIOClient client) { if (ex != null) { ex.printStackTrace(); return; } client.setReconnectCallback(new ReconnectCallback() { @Override public void onReconnect() { // TODO Auto-generated method stub } }); client.setDisconnectCallback(new DisconnectCallback() { @Override public void onDisconnect(Exception arg0) { // TODO Auto-generated method stub } }); client.setErrorCallback(new ErrorCallback() { @Override public void onError(String arg0) { // TODO Auto-generated method stub } }); client.on("event", new EventCallback() { @Override public void onEvent(JSONArray jsonArray, Acknowledge acknowledge) { ///bla bla } }); ScreenChat.mClient = client; } };

    Read the article

  • Returning a mock object from a mock object

    - by Songo
    I'm trying to return an object when mocking a parser class. This is the test code using PHPUnit 3.7 //set up the result object that I want to be returned from the call to parse method $parserResult= new ParserResult(); $parserResult->setSegment('some string'); //set up the stub Parser object $stubParser=$this->getMock('Parser'); $stubParser->expects($this->any()) ->method('parse') ->will($this->returnValue($parserResult)); //injecting the stub to my client class $fileHeaderParser= new FileWriter($stubParser); $output=$fileParser->writeStringToFile(); Inside my writeStringToFile() method I'm using $parserResult like this: writeStringToFile(){ //Some code... $parserResult=$parser->parse(); $segment=$parserResult->getSegment();//that's why I set the segment in the test. } Should I mock ParserResult in the first place, so that the mock returns a mock? Is it good design for mocks to return mocks? Is there a better approach to do this all?!

    Read the article

  • The counter doesnt seem to increase when ever the edittext changes

    - by Mabulhuda
    Im using Edit-texts and i need when ever an edit-text is changed to increment a counter by one but the counter isnt working , I mean the app starts and everything but the counter doesnt seem to change please help here is the code public class Numersys extends Activity implements TextWatcher { EditText mark1 ,mark2, mark3,mark4,mark5,mark6 , hr1 ,hr2,hr3,hr4,hr5,hr6; EditText passed, currentavg; TextView tvnewavg ; Button calculate; double marks , curAVG , NewAVG ; String newCumAVG; int counter , hrs , curHr , NewHr; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.numersys); mark1=(EditText)findViewById(R.id.mark1n); mark2=(EditText)findViewById(R.id.mark2n); mark3=(EditText)findViewById(R.id.mark3n); mark4=(EditText)findViewById(R.id.mark4n); mark5=(EditText)findViewById(R.id.mark5n); mark6=(EditText)findViewById(R.id.mark6n); hr1=(EditText)findViewById(R.id.ethour1); hr2=(EditText)findViewById(R.id.ethour2); hr3=(EditText)findViewById(R.id.ethour3); hr4=(EditText)findViewById(R.id.ethour4); hr5=(EditText)findViewById(R.id.ethour5); hr6=(EditText)findViewById(R.id.ethour6); passed=(EditText)findViewById(R.id.etPassCn); currentavg=(EditText)findViewById(R.id.etCavgn); tvnewavg=(TextView)findViewById(R.id.tvcAVGn); mark1.addTextChangedListener(this); mark2.addTextChangedListener(this); mark3.addTextChangedListener(this); mark4.addTextChangedListener(this); mark5.addTextChangedListener(this); mark6.addTextChangedListener(this); calculate=(Button)findViewById(R.id.bAvgCalcn); @Override public void onClick(View arg0) { // TODO Auto-generated method stub switch(arg0.getId()) { case 0: break; case 1: hrs=Integer.valueOf(hr1.getText().toString()); marks=Double.valueOf(mark1.getText().toString())*Integer.valueOf(hr1.getText().toString()); curHr=Integer.valueOf(passed.getText().toString()); curAVG=Double.valueOf(currentavg.getText().toString())*curHr; NewHr= curHr+hrs; NewAVG= (marks+curAVG)/NewHr; break; case 2: hrs=Integer.valueOf(hr1.getText().toString())+Integer.valueOf(hr2.getText().toString()); marks=Double.valueOf(mark1.getText().toString())*Integer.valueOf(hr1.getText().toString()) +Double.valueOf(mark2.getText().toString())*Integer.valueOf(hr2.getText().toString()); curHr=Integer.valueOf(passed.getText().toString()); curAVG=Double.valueOf(currentavg.getText().toString())*curHr; NewHr= curHr+hrs; NewAVG= (marks+curAVG)/NewHr; break; case 3: hrs=Integer.valueOf(hr1.getText().toString())+Integer.valueOf(hr2.getText().toString()) +Integer.valueOf(hr3.getText().toString()); marks=Double.valueOf(mark1.getText().toString())*Integer.valueOf(hr1.getText().toString()) +Double.valueOf(mark2.getText().toString())*Integer.valueOf(hr2.getText().toString()) +Double.valueOf(mark3.getText().toString())*Integer.valueOf(hr3.getText().toString()); curHr=Integer.valueOf(passed.getText().toString()); curAVG=Double.valueOf(currentavg.getText().toString())*curHr; NewHr= curHr+hrs; NewAVG= (marks+curAVG)/NewHr; break; case R.id.bAvgCalcn: newCumAVG=String.valueOf(NewAVG); tvnewavg.setText(newCumAVG); } } }); } @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub if(mark1.hasFocus()) { counter = counter+1; } if(mark2.hasFocus()) { counter = counter+1; } if(mark3.hasFocus()) { counter = counter+1; } if(mark4.hasFocus()) { counter = counter+1; } if(mark5.hasFocus()) { counter = counter+1; } if(mark6.hasFocus()) { counter = counter+1; } }

    Read the article

  • Data won't save to SQL database, getting error "close() was never explicitly called on database"

    - by SnowLeppard
    I have a save button in the activity where the user enters data which does this: String subjectName = etName.getText().toString(); String subjectColour = etColour.getText().toString(); SQLDatabase entrySubject = new SQLDatabase(AddSubject.this); entrySubject.open(); entrySubject.createSubjectEntry(subjectName, subjectColour); entrySubject.close(); Which refers to this SQL database class: package com.***.schooltimetable; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class SQLDatabase { public static final String KEY_SUBJECTS_ROWID = "_id"; public static final String KEY_SUBJECTNAME = "name"; public static final String KEY_COLOUR = "colour"; private static final String DATABASE_NAME = "Database"; private static final String DATABASE_TABLE_SUBJECTS = "tSubjects"; private static final int DATABASE_VERSION = 1; private DbHelper ourHelper; private final Context ourContext; private SQLiteDatabase ourDatabase; private static class DbHelper extends SQLiteOpenHelper { public DbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("CREATE TABLE " + DATABASE_TABLE_SUBJECTS + " (" + KEY_SUBJECTS_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_SUBJECTNAME + " TEXT NOT NULL, " + KEY_COLOUR + " TEXT NOT NULL);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_SUBJECTS); onCreate(db); } } public SQLDatabase(Context c) { ourContext = c; } public SQLDatabase open() throws SQLException { ourHelper = new DbHelper(ourContext); ourDatabase = ourHelper.getWritableDatabase(); return this; } public void close() { ourHelper.close(); } public long createSubjectEntry(String subjectName, String subjectColour) { // TODO Auto-generated method stub ContentValues cv = new ContentValues(); cv.put(KEY_SUBJECTNAME, subjectName); cv.put(KEY_COLOUR, subjectColour); return ourDatabase.insert(DATABASE_TABLE_SUBJECTS, null, cv); } public String[][] getSubjects() { // TODO Auto-generated method stub String[] Columns = new String[] { KEY_SUBJECTNAME, KEY_COLOUR }; Cursor c = ourDatabase.query(DATABASE_TABLE_SUBJECTS, Columns, null, null, null, null, null); String[][] Result = new String[1][]; // int iRow = c.getColumnIndex(KEY_LESSONS_ROWID); int iName = c.getColumnIndex(KEY_SUBJECTNAME); int iColour = c.getColumnIndex(KEY_COLOUR); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { Result[0][c.getPosition()] = c.getString(iName); Result[1][c.getPosition()] = c.getString(iColour); Settings.subjectCount = c.getPosition(); TimetableEntry.subjectCount = c.getPosition(); } return Result; } This class has other variables and other variations of the same methods for multiple tables in the database, i've cut out the irrelevant ones. I'm not sure what I need to close and where, I've got the entrySubject.close() in my activity. I used the methods for the database from the NewBoston tutorials. Can anyone see what I've done wrong, or where my problem is? Thanks.

    Read the article

  • Android: Programatically Add UI Elements to a View

    - by Shivan Raptor
    My view is written as follow: package com.mycompany; import android.view.View; import java.util.concurrent.TimeUnit; import java.util.ArrayList; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.util.AttributeSet; import android.graphics.Paint; import android.graphics.Point; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.widget.*; public class GameEngineView extends View implements SensorEventListener { GameLoop gameloop; String txt_acc; float accY; ArrayList<Point> bugPath; private SensorManager sensorManager; private class GameLoop extends Thread { private volatile boolean running = true; public void run() { while (running) { try { TimeUnit.MILLISECONDS.sleep(1); postInvalidate(); pause(); } catch (InterruptedException ex) { running = false; } } } public void pause() { running = false; } public void start() { running = true; run(); } public void safeStop() { running = false; interrupt(); } } public void unload() { gameloop.safeStop(); } public GameEngineView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub init(context); } public GameEngineView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub init(context); } public GameEngineView(Context context) { super(context); // TODO Auto-generated constructor stub init(context); } private void init(Context context) { txt_acc = ""; // Adding SENSOR sensorManager=(SensorManager)context.getSystemService(Context.SENSOR_SERVICE); // add listener. The listener will be HelloAndroid (this) class sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); // Adding UI Elements : How ? Button btn_camera = new Button(context); btn_camera.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT)); btn_camera.setClickable(true); btn_camera.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { System.out.println("clicked the camera."); } }); gameloop = new GameLoop(); gameloop.run(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub //super.onMeasure(widthMeasureSpec, heightMeasureSpec); System.out.println("Width " + widthMeasureSpec); setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub // super.onDraw(canvas); Paint p = new Paint(); p.setColor(Color.WHITE); p.setStyle(Paint.Style.FILL); p.setAntiAlias(true); p.setTextSize(30); canvas.drawText("|[ " + txt_acc + " ]|", 50, 500, p); gameloop.start(); } public void onAccuracyChanged(Sensor sensor,int accuracy){ } public void onSensorChanged(SensorEvent event){ if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){ //float x=event.values[0]; accY =event.values[1]; //float z=event.values[2]; txt_acc = "" + accY; } } } I would like to add a Button to the scene, but I don't know how to. Can anybody give me some lights? UPDATE: Here is my Activity : public class MyActivity extends Activity { private GameEngineView gameEngine; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // add Game Engine gameEngine = new GameEngineView(this); setContentView(gameEngine); gameEngine.requestFocus(); } }

    Read the article

  • How to make condition inside getView of Custom BaseAdapter

    - by user1501150
    I want to make a Custom ListView with Custom BaseAdapter, where the the status=1,I want to show a CheckBox, and else I want to show a textView.. My given condition is: if (NewtheStatus == 1) { alreadyOrderText .setVisibility(TextView.GONE); } else{ checkBox.setVisibility(CheckBox.GONE); } But Some times I obtain some row that has neither checkBox nor TextView. The Code of my Custom BaseAdapter is given below . private class MyCustomAdapter extends BaseAdapter { private static final int TYPE_ITEM = 0; private static final int TYPE_ITEM_WITH_HEADER = 1; // private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1; private ArrayList<WatchListAllEntity> mData = new ArrayList(); private LayoutInflater mInflater; private ArrayList<WatchListAllEntity> items = new ArrayList<WatchListAllEntity>(); public MyCustomAdapter(Context context, ArrayList<WatchListAllEntity> items) { mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void addItem(WatchListAllEntity watchListAllEntity) { // TODO Auto-generated method stub items.add(watchListAllEntity); } public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; final int position1 = position; if (v == null) { LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.listitempict, null); } watchListAllEntity = new WatchListAllEntity(); watchListAllEntity = items.get(position); Log.i("position: iteamsLength ", position + ", " + items.size()); if (watchListAllEntity != null) { ImageView itemImage = (ImageView) v .findViewById(R.id.imageviewproduct); if (watchListAllEntity.get_thumbnail_image_url1() != null) { Drawable image = ImageOperations(watchListAllEntity .get_thumbnail_image_url1().replace(" ", "%20"), "image.jpg"); // itemImage.setImageResource(R.drawable.icon); if (image != null) { itemImage.setImageDrawable(image); itemImage.setAdjustViewBounds(true); } else { itemImage.setImageResource(R.drawable.iconnamecard); } Log.i("status_ja , status", watchListAllEntity.get_status_ja() + " ," + watchListAllEntity.getStatus()); int NewtheStatus = Integer.parseInt(watchListAllEntity .getStatus()); CheckBox checkBox = (CheckBox) v .findViewById(R.id.checkboxproduct); TextView alreadyOrderText = (TextView) v .findViewById(R.id.alreadyordertext); if (NewtheStatus == 1) { alreadyOrderText .setVisibility(TextView.GONE); } else{ checkBox.setVisibility(CheckBox.GONE); } Log.i("Loading ProccardId: ", watchListAllEntity.get_proc_card_id() + ""); checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { WatchListAllEntity watchListAllEntity2 = items .get(position1); Log.i("Position: ", position1 + ""); // TODO Auto-generated method stub if (isChecked) { Constants.orderList.add(watchListAllEntity2 .get_proc_card_id()); Log.i("Proc Card Id Add: ", watchListAllEntity2 .get_proc_card_id() + ""); } else { Constants.orderList.remove(watchListAllEntity2 .get_proc_card_id()); Log.i("Proc Card Id Remove: ", watchListAllEntity2.get_proc_card_id() + ""); } } }); } } return v; } private Drawable ImageOperations(String url, String saveFilename) { try { InputStream is = (InputStream) this.fetch(url); Drawable d = Drawable.createFromStream(is, "src"); return d; } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } } public Object fetch(String address) throws MalformedURLException, IOException { URL url = new URL(address); Object content = url.getContent(); return content; } public int getCount() { // TODO Auto-generated method stub int sizef=items.size(); Log.i("Size", sizef+""); return items.size(); } public Object getItem(int position) { // TODO Auto-generated method stub return items.get(position); } public long getItemId(int position) { // TODO Auto-generated method stub return position; } }

    Read the article

  • Process: Unable to start service com.google.android.gms.checkin.CheckinService with Intent

    - by AndyRoid
    I'm trying to build a Google map application but keep receiving this in my LogCat. I have all the permissions and meta-data set in my manifest, but am still dumbfounded by this error. Have looked everywhere on SO for this specific error but found nothing relating to com.google.android.gms.checkin A little bit about my structural hierarchy. MainActivity extends ActionBarActivity with three tabs underneath actionbar. Each tab has it's own fragment. On the gMapFragment I create a GPSTrack object from my GPSTrack class which extends Service and implements LocationListener. The problem is that when I start the application I get this message: I have all my libraries imported properly and I even added the google-play-services.jar into my libs folder. I also installed Google Play Services APKs through CMD onto my emulator. Furthermore the LocationManager lm = = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); in my GPSTrack class always returns null. Why is this and how can I fix these issues? Would appreciate an explanation along with solution too, I want to understand what's going on here. ============== Code: gMapFragment.java public class gMapFragment extends SupportMapFragment { private final String TAG = "gMapFragment"; private GoogleMap mMap; protected SupportMapFragment mapFrag; private Context mContext = getActivity(); private static View view; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (view != null) { ViewGroup parent = (ViewGroup) view.getParent(); if (parent != null) { parent.removeView(view); } } try { super.onCreateView(inflater, container, savedInstanceState); view = inflater.inflate(R.layout.fragment_map, container, false); setupGoogleMap(); } catch (Exception e) { /* * Map already there , just return as view */ } return view; } private void setupGoogleMap() { mapFrag = (SupportMapFragment) getFragmentManager().findFragmentById( R.id.mapView); if (mapFrag == null) { FragmentManager fragManager = getFragmentManager(); FragmentTransaction fragTransaction = fragManager .beginTransaction(); mapFrag = SupportMapFragment.newInstance(); fragTransaction.replace(R.id.mapView, mapFrag).commit(); } if (mapFrag != null) { mMap = mapFrag.getMap(); if (mMap != null) { setupMap(); mMap.setOnMapClickListener(new OnMapClickListener() { @Override public void onMapClick(LatLng point) { // TODO your click stuff on map } }); } } } @Override public void onAttach(Activity activity) { super.onAttach(activity); Log.d("Attach", "on attach"); } @Override public void onDetach() { super.onDetach(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } @Override public void onDestroy() { super.onDestroy(); } private void setupMap() { GPSTrack gps = new GPSTrack(mContext); // Enable MyLocation layer of google map mMap.setMyLocationEnabled(true); Log.d(TAG, "MyLocation enabled"); // Set Map type mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); // Grab current location **ERROR HERE/Returns Null** Location location = gps.getLocation(); Log.d(TAG, "Grabbing location..."); if (location != null) { Log.d(TAG, "location != null"); // Grab Latitude and Longitude double latitude = location.getLatitude(); double longitude = location.getLongitude(); Log.d(TAG, "Getting lat, long.."); // Initialize LatLng object LatLng latLng = new LatLng(latitude, longitude); Log.d(TAG, "LatLng initialized"); // Show current location on google map mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); // Zoom in on google map mMap.animateCamera(CameraUpdateFactory.zoomTo(20)); mMap.addMarker(new MarkerOptions().position( new LatLng(latitude, longitude)).title("You are here.")); } else { gps.showSettingsAlert(); } } } GPSTrack.java public class GPSTrack extends Service implements LocationListener{ private final Context mContext; private boolean isGPSEnabled = false; //See if network is connected to internet private boolean isNetworkEnabled = false; //See if you can grab the location private boolean canGetLocation = false; protected Location location = null; protected double latitude; protected double longitude; private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 Meters private static final long MINIMUM_TIME_CHANGE_FOR_UPDATES = 1000 * 60 * 1; //1 minute protected LocationManager locationManager; public GPSTrack(Context context) { this.mContext = context; getLocation(); } public Location getLocation() { try { //Setup locationManager for controlling location services **ERROR HERE/Return Null** locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE); //See if GPS is enabled isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); //See if Network is connected to the internet or carrier service isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled && !isNetworkEnabled) { Toast.makeText(getApplicationContext(), "No Network Provider Available", Toast.LENGTH_SHORT).show(); } else { this.canGetLocation = true; if (isNetworkEnabled) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_CHANGE_FOR_UPDATES, MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS", "GPS Enabled"); if (locationManager != null) { location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } catch (Exception e) { e.printStackTrace(); } return location; } public void stopUsingGPS() { if (locationManager != null) { locationManager.removeUpdates(GPSTrack.this); } } public double getLatitude() { if (location != null) { latitude = location.getLatitude(); } return latitude; } public double getLongitude() { if (location != null) { longitude = location.getLongitude(); } return longitude; } public boolean canGetLocation() { return this.canGetLocation; } public void showSettingsAlert() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); //AlertDialog title alertDialog.setTitle("GPS Settings"); //AlertDialog message alertDialog.setMessage("GPS is not enabled. Do you want to go to Settings?"); alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); mContext.startActivity(i); } }); alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub dialog.cancel(); } }); alertDialog.show(); } @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } } logcat 06-08 22:35:03.441: E/AndroidRuntime(1370): FATAL EXCEPTION: main 06-08 22:35:03.441: E/AndroidRuntime(1370): Process: com.google.android.gms, PID: 1370 06-08 22:35:03.441: E/AndroidRuntime(1370): java.lang.RuntimeException: Unable to start service com.google.android.gms.checkin.CheckinService@b1094e48 with Intent { cmp=com.google.android.gms/.checkin.CheckinService }: java.lang.SecurityException: attempting to read gservices without permission: Neither user 10053 nor current process has com.google.android.providers.gsf.permission.READ_GSERVICES. 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2719) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.app.ActivityThread.access$2100(ActivityThread.java:135) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.os.Handler.dispatchMessage(Handler.java:102) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.os.Looper.loop(Looper.java:136) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.app.ActivityThread.main(ActivityThread.java:5017) 06-08 22:35:03.441: E/AndroidRuntime(1370): at java.lang.reflect.Method.invokeNative(Native Method) 06-08 22:35:03.441: E/AndroidRuntime(1370): at java.lang.reflect.Method.invoke(Method.java:515) 06-08 22:35:03.441: E/AndroidRuntime(1370): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 06-08 22:35:03.441: E/AndroidRuntime(1370): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 06-08 22:35:03.441: E/AndroidRuntime(1370): at dalvik.system.NativeStart.main(Native Method) 06-08 22:35:03.441: E/AndroidRuntime(1370): Caused by: java.lang.SecurityException: attempting to read gservices without permission: Neither user 10053 nor current process has com.google.android.providers.gsf.permission.READ_GSERVICES. 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.app.ContextImpl.enforce(ContextImpl.java:1685) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.app.ContextImpl.enforceCallingOrSelfPermission(ContextImpl.java:1714) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.content.ContextWrapper.enforceCallingOrSelfPermission(ContextWrapper.java:572) 06-08 22:35:03.441: E/AndroidRuntime(1370): at imq.c(SourceFile:107) 06-08 22:35:03.441: E/AndroidRuntime(1370): at imq.a(SourceFile:121) 06-08 22:35:03.441: E/AndroidRuntime(1370): at imq.a(SourceFile:227) 06-08 22:35:03.441: E/AndroidRuntime(1370): at bwq.c(SourceFile:166) 06-08 22:35:03.441: E/AndroidRuntime(1370): at com.google.android.gms.checkin.CheckinService.a(SourceFile:237) 06-08 22:35:03.441: E/AndroidRuntime(1370): at com.google.android.gms.checkin.CheckinService.onStartCommand(SourceFile:211) 06-08 22:35:03.441: E/AndroidRuntime(1370): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2702) AndroidManifest <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19" /> <uses-permission android:name="com.curio.permission.MAPS_RECEIVE" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> <uses-feature android:name="android.hardware.camera" android:required="true" /> <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.app.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AI........................" /> </application>

    Read the article

  • facebook connect for android returns a blank login screen?

    - by jonney
    Hi, i am trying to use the old facebook connect authentication to authenticate my android client to get the necessary session id's and other credentials thats needed to start using the web service of facebook. the issue i am having is that when my android application launces and tries to load the login page for facebook, that very same login page is blank and it only displays the the facebook logo as the title of the screen. No login fields or buttons are visible leaving me nowhere to login and authenticate a user. i have tried two API's one is facebook connect api for android http://code.google.com/p/fbconnect-android/ and the other one is the official android facebook sdk that is recommended to be used instead of the previous one i have just mentioned https://github.com/facebook/facebook-android-sdk/ . please see the image below of how it looks like on my app. Here is code that uses the latest android sdk facebook: /** * Authenticate facebook network */ private void authenticateFacebook() { // TODO: move this away from this activty class into some kind of // helper/wrapper class Log.d(TAG, "Clicked on the facebook"); Facebook facebook = new Facebook(OAUTH_KEY_FACEBOOK_API); facebook.authorize(this, new AuthorizeListener()); } class AuthorizeListener implements DialogListener{ @Override public void onComplete(Bundle values) { // TODO Auto-generated method stub Log.d(TAG, "finished authorizing facebook user"); } @Override public void onFacebookError(FacebookError e) { // TODO Auto-generated method stub } @Override public void onError(DialogError e) { // TODO Auto-generated method stub } @Override public void onCancel() { // TODO Auto-generated method stub } } And a simple example of how to use it: http://developers.facebook.com/docs/guides/mobile/ My code is more or less identical to the above example. edit: i did not catch what logcat was inputing in my first attempted at my code above but their was no exceptions or warnings thrown at the time. just a blank page. i then tried it again and diddnt touch my code and what happens now is that a loading dialogue view pops up and stays their for a few minutes until the facebook windows disapears and the logcat outputs the error below: 11-18 17:26:19.913: DEBUG/Facebook-WebView(783): Webview loading URL: https://www.facebook.com/dialog/oauth?type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess&display=touch&client_id=e??????????????????? 11-18 17:27:01.756: DEBUG/Facebook-authorize(783): Login failed: com.kc.unity.agent.util.oauth.facebook.DialogError: The connection to the server was unsuccessful. 11-18 17:27:01.783: DEBUG/Facebook-WebView(783): Webview loading URL: https://www.facebook.com/dialog/oauth?type=user_agent&redirect_uri=fbconnect%3A%2F%2Fsuccess&display=touch&client_id=??????????????? please note that the client id i have amended for obvious reasons but the rest of the logcat is untouched

    Read the article

  • Testing Paypal error messages using ActiveMerchant

    - by vrish88
    Hello, Is there a way to test your application's processing and handling of Paypal generated credit card errors? I'd like to verify that my application can handle a declined credit card or something like that. So is there a way to have Paypal send an error message? Or would it be better to generate a stub and use it in the testing environment? If this is the better way, how would one generate a stub? Thanks!

    Read the article

  • Android Application Crashel

    - by deewangan
    hello everyone, i am trying to run an application on an android emulator, but it crashes. i am following a howto i don't know what to do, it just crashes. other applications are running fine, can anyone tell me what i am doing wrong.here is the code: public class Finder extends Activity { /** Called when the activity is first created. */ private LocationManager myLocationManager; private LocationListener myLocationListener; private TextView myLatitude, myLongitude; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myLatitude = (TextView)findViewById(R.id.Latitude); myLongitude = (TextView)findViewById(R.id.Longitude); myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); myLocationListener = new MyLocationListener(); myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,myLocationListener); myLatitude.setText(String.valueOf( myLocationManager.getLastKnownLocation( LocationManager.GPS_PROVIDER).getLatitude())); myLongitude.setText(String.valueOf( myLocationManager.getLastKnownLocation( LocationManager.GPS_PROVIDER).getLongitude())); } private class MyLocationListener implements LocationListener{ public void onLocationChanged(Location argLocation) { // TODO Auto-generated method stub myLatitude.setText(String.valueOf( argLocation.getLatitude())); myLongitude.setText(String.valueOf( argLocation.getLongitude())); } public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } }; } i looked in the logcat after running the application, it seems that the following lines are cause of the problem but i don't understand it:( 01-18 22:12:46.017: WARN/dalvikvm(1091): threadid=3: thread exiting with uncaught exception (group=0x4001aa28) 01-18 22:12:46.017: ERROR/AndroidRuntime(1091): Uncaught handler: thread main exiting due to uncaught exception 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): java.lang.RuntimeException: Unable to start activity ComponentInfo{pro.googleLocation/pro.googleLocation.Finder}: java.lang.NullPointerException 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2401) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at android.app.ActivityThread.access$2100(ActivityThread.java:116) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at android.os.Handler.dispatchMessage(Handler.java:99) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at android.os.Looper.loop(Looper.java:123) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at android.app.ActivityThread.main(ActivityThread.java:4203) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at java.lang.reflect.Method.invokeNative(Native Method) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at java.lang.reflect.Method.invoke(Method.java:521) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at dalvik.system.NativeStart.main(Native Method) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): Caused by: java.lang.NullPointerException 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at pro.googleLocation.Finder.onCreate(Finder.java:28) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364) 01-18 22:12:46.037: ERROR/AndroidRuntime(1091): ... 11 more

    Read the article

  • Do we really need isolation frameworks to create stubs?

    - by Sandbox
    I have read this: http://martinfowler.com/articles/mocksArentStubs.html My concepts about a stub and a mock are clear. I understand the need of isolation frameworks like moq, rhinomocks and like to create a mock object. As mocks, participate in actual verfication of expectations. But why do we need these frameworks to create stubs. I would rather prefer rolling out a hand created stub and use it in various fixtures.

    Read the article

  • Error while compiling the Xcode project (IPhone)

    - by Sridhar
    Hello, I added ffmpeg iphone port into my library and I can able to use a few of its functions like avcodec_init(),.. without any errors. But when I include this function call "avcodec_register_all" Xcode is giving error after compilation The error message is : *--------------- ld: ldr 12-bit displacement out of range (4276 max +/-4096) in _CFRelease$stub in _CFRelease$stub from /Users/foxit/Documents/CameraTest/build/CameraTest.build/Debug-iphoneos/CameraTest.build/Objects-normal/armv6/CameraTest Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/gcc-4.2 failed with exit code 1 *------------- Does anyone know whats wrong with this ? Regards, Raghu

    Read the article

  • how to invoke a webservice from one container in another container in glassfish

    - by vinny
    I have webservices deployed on two containers in two separate servers A and B. A webMethod in 'Server A' needs to invoke a webmethod in 'Server B'. I have created a client stub for Sever B. Im trying to make 'Server A' use this client stub and talk to Server B. I get an exception while trying to instantiate the port object specifically at : service.getABCBeanPort(); (using JAX-WS library) Is my approach correct? Is there any better way of invoking a webservice on a remote server?

    Read the article

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