Search Results

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

Page 8/27 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • RMI java doesn't create skeleton class

    - by pavithra
    I wrote a remote service MyremoteImpl.java and used following command after compiled it. rmic MyRemoteImpl I learned that this method suppose to create stub class and a skeleton class but I can only see the stub class, why is that? The other problem I faced after run rmiregistry I started the service but it gives following error, I doubt I get this error as I'm missing skeleton class? java.net.MalformedURLException: invalid URL String: Remote Hello at java.rmi.Naming.parseURL(Unknown Source) at java.rmi.Naming.rebind(Unknown Source) at RMIservice.MyRemoteImpl.main(MyRemoteImpl.java:22) Caused by: java.net.URISyntaxException: Illegal character in path at index 6: Remote Hello at java.net.URI$Parser.fail(Unknown Source) at java.net.URI$Parser.checkChars(Unknown Source) at java.net.URI$Parser.parseHierarchical(Unknown Source) at java.net.URI$Parser.parse(Unknown Source) at java.net.URI.<init>(Unknown Source) at java.rmi.Naming.intParseURL(Unknown Source) ... 3 more Please help me to solve this, Thanx in advance!!!

    Read the article

  • How can i do the same thing with Gallery in Android

    - by Maxood
    I am navigating images with the clicks of next and previous buttons.Here is my code: package com.myapps.imagegallery; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class ImageGallery extends Activity { /** Called when the activity is first created. */ int imgs[] = {R.drawable.bluehills,R.drawable.lilies,R.drawable.sunset,R.drawable.winter}; String desc[] = {"Blue Hills", "Lillies", "Sunset", "Winter" }; int counter=0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ImageView imgView = (ImageView)findViewById(R.id.ImageView01); imgView.setImageResource(imgs[counter]); final TextView tvDesc = (TextView)findViewById(R.id.tvDesc); Button btnNext = (Button)findViewById(R.id.btnNext); btnNext.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View arg0) { try{ // TODO Auto-generated method stub if (counter < desc.length -1) counter++; imgView.setImageResource(imgs[counter]); tvDesc.setText(desc[counter]); }catch(Exception e) { Toast.makeText(ImageGallery.this, e.toString(), Toast.LENGTH_SHORT).show(); } } }); Button btnPrev = (Button)findViewById(R.id.btnPre); btnPrev.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub try{ // TODO Auto-generated method stub if (counter > 0) counter--; imgView.setImageResource(imgs[counter]); tvDesc.setText(desc[counter]); }catch(Exception e) { Toast.makeText(ImageGallery.this, e.toString(), Toast.LENGTH_SHORT).show(); } }}); } } <?xml version="1.0" encoding="utf-8"?> <AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id="@+id/ImageView01" android:layout_x="70dip" android:layout_width="200px" android:layout_height="200px" android:layout_y="90dip" > </ImageView> <TextView android:id="@+id/tvDesc" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" android:layout_x="90px" android:layout_y="300px" /> <Button android:layout_x="47dip" android:layout_height="wrap_content" android:text="Previous" android:layout_width="100px" android:id="@+id/btnPre" android:layout_y="341dip"> </Button> <Button android:layout_x="190dip" android:layout_height="wrap_content" android:text="Next" android:layout_width="100px" android:id="@+id/btnNext" android:layout_y="341dip"> </Button> </AbsoluteLayout>

    Read the article

  • Java Box Class: Unsolvable: aligning components to the left or right

    - by user323186
    I have been trying to left align buttons contained in a Box to the left, with no success. They align left alright, but for some reason dont shift all the way left as one would imagine. I attach the code below. Please try compiling it and see for yourself. Seems bizarre to me. Thanks, Eric import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class MainGUI extends Box implements ActionListener{ //Create GUI Components Box centerGUI=new Box(BoxLayout.X_AXIS); Box bottomGUI=new Box(BoxLayout.X_AXIS); //centerGUI subcomponents JTextArea left=new JTextArea(), right=new JTextArea(); JScrollPane leftScrollPane = new JScrollPane(left), rightScrollPane = new JScrollPane(right); //bottomGUI subcomponents JButton encrypt=new JButton("Encrypt"), decrypt=new JButton("Decrypt"), close=new JButton("Close"), info=new JButton("Info"); //Create Menubar components JMenuBar menubar=new JMenuBar(); JMenu fileMenu=new JMenu("File"); JMenuItem open=new JMenuItem("Open"), save=new JMenuItem("Save"), exit=new JMenuItem("Exit"); int returnVal =0; public MainGUI(){ super(BoxLayout.Y_AXIS); initCenterGUI(); initBottomGUI(); initFileMenu(); add(centerGUI); add(bottomGUI); addActionListeners(); } private void addActionListeners() { open.addActionListener(this); save.addActionListener(this); exit.addActionListener(this); encrypt.addActionListener(this); decrypt.addActionListener(this); close.addActionListener(this); info.addActionListener(this); } private void initFileMenu() { fileMenu.add(open); fileMenu.add(save); fileMenu.add(exit); menubar.add(fileMenu); } public void initCenterGUI(){ centerGUI.add(leftScrollPane); centerGUI.add(rightScrollPane); } public void initBottomGUI(){ bottomGUI.setAlignmentX(LEFT_ALIGNMENT); //setBorder(BorderFactory.createLineBorder(Color.BLACK)); bottomGUI.add(encrypt); bottomGUI.add(decrypt); bottomGUI.add(close); bottomGUI.add(info); } @Override public void actionPerformed(ActionEvent arg0) { // find source of the action Object source=arg0.getSource(); //if action is of such a type do the corresponding action if(source==close){ kill(); } else if(source==open){ //CHOOSE FILE File file1 =chooseFile(); String input1=readToString(file1); System.out.println(input1); left.setText(input1); } else if(source==decrypt){ //decrypt everything in Right Panel and output in left panel decrypt(); } else if(source==encrypt){ //encrypt everything in left panel and output in right panel encrypt(); } else if(source==info){ //show contents of info file in right panel doInfo(); } else { System.out.println("Error"); //throw new UnimplementedActionException(); } } private void doInfo() { // TODO Auto-generated method stub } private void encrypt() { // TODO Auto-generated method stub } private void decrypt() { // TODO Auto-generated method stub } private String readToString(File file) { FileReader fr = null; try { fr = new FileReader(file); } catch (FileNotFoundException e1) { e1.printStackTrace(); } BufferedReader br=new BufferedReader(fr); String line = null; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } String input=""; while(line!=null){ input=input+"\n"+line; try { line=br.readLine(); } catch (IOException e) { e.printStackTrace(); } } return input; } private File chooseFile() { //Create a file chooser final JFileChooser fc = new JFileChooser(); returnVal = fc.showOpenDialog(fc); return fc.getSelectedFile(); } private void kill() { System.exit(0); } public static void main(String[] args) { // TODO Auto-generated method stub MainGUI test=new MainGUI(); JFrame f=new JFrame("Tester"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setJMenuBar(test.menubar); f.setPreferredSize(new Dimension(600,400)); //f.setUndecorated(true); f.add(test); f.pack(); f.setVisible(true); } }

    Read the article

  • Android: Playing sound when button clicked?

    - by gazeebo
    Hi all, I'm trying to play a sound file when a button is clicked but keeps getting an error. The error is "The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (new View.OnClickListener(){}, int)" Here's my code: @Override public void onClick(View v) { // TODO Auto-generated method stub Button zero = (Button)this.findViewById(R.id.btnZero); zero.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub mp = MediaPlayer.create(this, R.raw.mamacita_zero); } }); } Any help or tips would be appreciated. Thnx!

    Read the article

  • Does isolation frameworks (Moq, RhinoMock, etc) lead to test overspecification?

    - by Marius
    In Osherove's great book "The Art of Unit Testing" one of the test anti-patterns is over-specification which is basically the same as testing the internal state of the object instead of some expected output. To my experience, using Isolation frameworks can cause the same unwanted side effects as testing internal behavior because one tends to only implement the behavior necessary to make your stub interact with the object under test. Now if your implementation changes later on (but the contract remains the same), your test will suddenly break because you are expecting some data from the stub which was not implemented. So what do you think is the best approach to counter this? 1) Implement your stubs/mocks fully, this has the negative side-effect of potentially making your test less readable and also specifying more than necessary to make your test pass. 2) Favor manual, fully implemented fakes. 3) Implement your stubs/fakes so that they make your test just pass, and then deal with the brittleness that this might introduce.

    Read the article

  • Examining a lambda expression at runtime in C#

    - by Ben Aston
    I have a method Get on a type MyType1 accepting a Func<MyType2, bool> as a parameter. An example of its use: mytype1Instance.Get(x => x.Guid == guid)); I would like create a stub implementation of the method Get that examines the incoming lambda expression and determines what the value of guid is. Clearly the lambda could be "anything", but I'm happy for the stub to make an assumption about the lambda, that it is trying to match on the Guid property. How can I do this? I suspect it involves the use of the built-in Expression type?

    Read the article

  • using AsyncTask class for parallel operationand displaying a progress bar

    - by Kumar
    I am displaying a progress bar using Async task class and simulatneously in parallel operation , i want to retrieve a string array from a function of another class that takes some time to return the string array. The problem is that when i place the function call in doing backgroung function of AsyncTask class , it gives an error in Doing Background and gives the message as cant change the UI in doing Background .. Therefore , i placed the function call in post Execute method of Asynctask class . It doesnot give an error but after the progress bar has reached 100% , then the screen goes black and takes some time to start the new activity. How can i display the progress bar and make the function call simultaneously.??plz help , m in distress here is the code package com.integrated.mpr; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class Progess extends Activity implements OnClickListener{ static String[] display = new String[Choose.n]; Button bprogress; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.progress); bprogress = (Button) findViewById(R.id.bProgress); bprogress.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch(v.getId()){ case R.id.bProgress: String x ="abc"; new loadSomeStuff().execute(x); break; } } public class loadSomeStuff extends AsyncTask<String , Integer , String>{ ProgressDialog dialog; protected void onPreExecute(){ dialog = new ProgressDialog(Progess.this); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setMax(100); dialog.show(); } @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub for(int i = 0 ;i<40;i++){ publishProgress(5); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } dialog.dismiss(); String y ="abc"; return y; } protected void onProgressUpdate(Integer...progress){ dialog.incrementProgressBy(progress[0]); } protected void onPostExecute(String result){ display = new Logic().finaldata(); Intent openList = new Intent("com.integrated.mpr.SENSITIVELIST"); startActivity(openList); } } }

    Read the article

  • Difference in techniques for setting a stubbed method's return value with Rhino Mocks

    - by CRice
    What is the main difference between these following two ways to give a method some fake implementation? I was using the second way fine in one test but in another test the behaviour can not be achieved unless I go with the first way. These are set up via: IMembershipService service = test.Stub<IMembershipService>(); so (the first), using (test.Record()) //test is MockRepository instance { service.GetUser("dummyName"); LastCall.Return(new LoginUser()); } vs (the second). service.Stub(r => r.GetUser("dummyName")).Return(new LoginUser()); Edit The problem is that the second technique returns null in the test, when I expect it to return a new LoginUser. The first technique behaves as expected by returning a new LoginUser. All other test code used in both cases is identical.

    Read the article

  • How to pass Remote Interface (aidl) throughout Activities ?

    - by Spredzy
    Hi All, I am developing an application using services and Remote interface. I have a question about passing the reference of my Remote interface throughout Activities. In my first Activity, I bind my service with my activity, in order to get a reference to my interface I use private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName arg0, IBinder service) { x = X.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName arg0) { // TODO Auto-generated method stub } }; x being the reference to my interface. Now I would like to access this interface from another activity, I see two ways to do it but I don't know which one is the "proper" way to do it : passing x with my intent when I call the new Activity redo this.bindService(new Intent(y.this,z.class), mConnection, Context.BIND_AUTO_CREATE); in the onCreate() of my new Activity What would you advice me to do ?

    Read the article

  • Returnimng collection of interfaces

    - by apoorv020
    I have created the following interface public interface ISolutionSpace { public boolean isFeasible(); public boolean isSolution(); public Set<ISolutionSpace> generateChildren(); } However, in the implementation of ISolutionSpace in a class called EightQueenSolutionSpace, I am going to return a set of EightQueenSolutionSpace instances, like the following stub: @Override public Set<ISolutionSpace> generateChildren() { return new HashSet<EightQueenSolutionSpace>(); } However this stub wont compile. What changes do I need to make? EDIT: I tried 'HashSet' as well and had tried using the extends keyword. However since 'ISolutionSpace' is an interface and EightQueenSolutionSpace is an implementation(and not a subclass) of 'ISolutionSpace', it is still not working.

    Read the article

  • Java compiler rejects variable declaration with parameterized inner class

    - by Johansensen
    I have some Groovy code which works fine in the Groovy bytecode compiler, but the Java stub generated by it causes an error in the Java compiler. I think this is probably yet another bug in the Groovy stub generator, but I really can't figure out why the Java compiler doesn't like the generated code. Here's a truncated version of the generated Java class (please excuse the ugly formatting): @groovy.util.logging.Log4j() public abstract class AbstractProcessingQueue <T> extends nz.ac.auckland.digitizer.AbstractAgent implements groovy.lang.GroovyObject { protected int retryFrequency; protected java.util.Queue<nz.ac.auckland.digitizer.AbstractProcessingQueue.ProcessingQueueMember<T>> items; public AbstractProcessingQueue (int processFrequency, int timeout, int retryFrequency) { super ((int)0, (int)0); } private enum ProcessState implements groovy.lang.GroovyObject { NEW, FAILED, FINISHED; } private class ProcessingQueueMember<E> extends java.lang.Object implements groovy.lang.GroovyObject { public ProcessingQueueMember (E object) {} } } The offending line in the generated code is this: protected java.util.Queue<nz.ac.auckland.digitizer.AbstractProcessingQueue.ProcessingQueueMember<T>> items; which produces the following compile error: [ERROR] C:\Documents and Settings\Administrator\digitizer\target\generated-sources\groovy-stubs\main\nz\ac\auckland\digitizer\AbstractProcessingQueue.java:[14,96] error: improperly formed type, type arguments given on a raw type The column index of 96 in the compile error points to the <T> parameterization of the ProcessingQueueMember type. But ProcessingQueueMember is not a raw type as the compiler claims, it is a generic type: private class ProcessingQueueMember <E> extends java.lang.Object implements groovy.lang.GroovyObject { ... I am very confused as to why the compiler thinks that the type Queue<ProcessingQueueMember<T>> is invalid. The Groovy source compiles fine, and the generated Java code looks perfectly correct to me too. What am I missing here? Is it something to do with the fact that the type in question is a nested class? (in case anyone is interested, I have filed this bug report relating to the issue in this question) Edit: Turns out this was indeed a stub compiler bug- this issue is now fixed in 1.8.9, 2.0.4 and 2.1, so if you're still having this issue just upgrade to one of those versions. :)

    Read the article

  • JNA array structure

    - by Burny
    I want to use a dll (IEC driver) in Java, for that I am using JNA. The problem in pseudo code: start the server allocate new memory for an array (JNA) client connect writing values from an array to the memory sending this array to the client client disconnect new client connect allocate new memory for an array (JNA) - JVM crash (EXCEPTION_ACCESS_VIOLATION) The JVM crash not by primitve data types and if the values will not writing from the array to the memory. the code in c: struct DataAttributeData CrvPtsArrayDAData = {0}; CrvPtsArrayDAData.ucType = DATATYPE_ARRAY; CrvPtsArrayDAData.pvData = XYValDAData; XYValDAData[0].ucType = FLOAT; XYValDAData[0].uiBitLength = sizeof(Float32)*8; XYValDAData[0].pvData = &(inUpdateValue.xVal); XYValDAData[1].ucType = FLOAT; XYValDAData[1].uiBitLength = sizeof(Float32)*8; XYValDAData[1].pvData = &(inUpdateValue.yVal); Send(&CrvPtsArrayDAData, 1); the code in Java: DataAttributeData[] data_array = (DataAttributeData[]) new DataAttributeData() .toArray(d.bitLength); for (DataAttributeData d_temp : data_array) { d_temp.data = new Memory(size / 8); d_temp.type = type_iec; d_temp.bitLength = size; d_temp.write(); } d.data = data_array[0].getPointer(); And then writing values whith this code: for (int i = 0; i < arraySize; i++) { DataAttributeData dataAttr = new DataAttributeData(d.data.share(i * d.size())); dataAttr.read(); dataAttr.data.setFloat(0, f[i]); dataAttr.write(); } the struct in c: struct DataAttributeData{ unsigned char ucType; int iArrayIndex; unsigned int uiBitLength; void * pvData;}; the struct in java: public static class DataAttributeData extends Structure { public DataAttributeData(Pointer p) { // TODO Auto-generated constructor stub super(p); } public DataAttributeData() { // TODO Auto-generated constructor stub super(); } public byte type; public int iArrayIndex; public int bitLength; public Pointer data; @Override protected List<String> getFieldOrder() { // TODO Auto-generated method stub return Arrays.asList(new String[] { "type", "iArrayIndex", "bitLength", "data" }); } } Can anybody help me?

    Read the article

  • Handling file upload in a non-blocking manner

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

    Read the article

  • how to redirect on youtube in androi

    - by rajshree
    public class MovieDescription extends Activity { Vibrator vibrator; TextView tv_title,tv_year,tv_banner,tv_desc; RatingBar ratingBar; ImageView iv_watch,iv_poster; private static final String TAG_CONTACTS = "Demo"; private static final String TAG_ID = "id"; private static final String TAG_TITLE = "title"; private static final String TAG_YEAR = "year"; private static final String TAG_RATING = "rating"; private static final String TAG_BANNER= "category"; private static final String TAG_DESC = "description"; private static final String TAG_URL = "url"; private static final String TAG_POSTER = "poster"; String id,title,year,rating,banner,description,poster, movieUrl; static JSONArray contacts = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.movie_description); initialize(); String movieDescUrl = "http://vaibhavtech.com/work/android/movie_description.php?id="+MainActivity.movie_Id; MovieDescriptionParser jParser = new MovieDescriptionParser(); JSONObject json = jParser.getJSONFromUrl(movieDescUrl); try { contacts = json.getJSONArray(TAG_CONTACTS); for (int i = 0; i < contacts.length(); i++) { /**********************************Value Parse FromUrl**********************************/ JSONObject c = contacts.getJSONObject(i); id = c.getString(TAG_ID); title = c.getString(TAG_TITLE); year = c.getString(TAG_YEAR); rating = c.getString(TAG_RATING); banner=c.getString(TAG_BANNER); description = c.getString(TAG_DESC); movieUrl = c.getString(TAG_URL); poster = c.getString(TAG_POSTER); /**********************************Valeu Assing to UI Component**********************************/ Log.i(id, title); } } catch (JSONException e) { e.printStackTrace(); } tv_title.setText(title); tv_year.setText(year); tv_banner.setText(banner); tv_desc.setText(description); Float rat=Float.parseFloat(rating); ratingBar.setRating(rat); Bitmap bimage= getBitmapFromURL("http://vaibhavtech.com/work/android/admin/upload/"+poster); iv_poster.setImageBitmap(bimage); iv_watch.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub vibrator.vibrate(40); LayoutInflater inflater=getLayoutInflater(); View view=inflater.inflate(R.layout.customtoast,(ViewGroup)findViewById(R.id.custom_toast_layout)); Toast toast=new Toast(getApplicationContext()); toast.setDuration(Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0); toast.setView(view); toast.show(); Intent intent=new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(movieUrl)); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub int currentapiVersion = android.os.Build.VERSION.SDK_INT; Log.i("Device Versoin is", ""+currentapiVersion); if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN){ ActionBar actionBar = getActionBar(); actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); getMenuInflater().inflate(R.menu.main, menu); } return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; case R.id.home: Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); Log.i("Home", "Press"); return true; } return super.onOptionsItemSelected(item); } public void initialize() { tv_banner=(TextView) findViewById(R.id.tv_movie_description_banner); tv_desc=(TextView) findViewById(R.id.tv_movie_description_decription); tv_title=(TextView) findViewById(R.id.tv_movie_description_name); tv_year=(TextView) findViewById(R.id.tv_movie_description_year); ratingBar=(RatingBar) findViewById(R.id.ratingBar1); iv_watch=(ImageView) findViewById(R.id.iv_movie_description_watch); iv_poster=(ImageView) findViewById(R.id.iv_movie_description_poster); vibrator=(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);; } public static Bitmap getBitmapFromURL(String src) { try { Log.i("src",src); URL url = new URL(src); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); Log.i("Bitmap","returned"); return myBitmap; } catch (IOException e) { e.printStackTrace(); Log.e("Exception",e.getMessage()); return null; } } } when i am clciking on watch now button its giving me 4 options -by mozilz,by chrome,by youtube, i want that when i click on watch now button it get redirect on youtube url link,..how can i do this please give me any suggetion.:(

    Read the article

  • Android camera to take multiple photos

    - by user2975407
    problem.java public class problem extends Activity { ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.problem); iv=(ImageView) findViewById(R.id.imageView1); Button b=(Button) findViewById(R.id.button1); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, 0); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); Bitmap bm=(Bitmap) data.getExtras().get("data"); iv.setImageBitmap(bm); } } From this code I can only take one photo and it displayed in the screen. **But I want to take more photos nearly 5 photos and display in the screen** Further I want to add these photos to MySQL database.please help me to do that.I am new to android

    Read the article

  • Solaris 11 Launch Blog Carnival Roundup

    - by constant
    Solaris 11 is here! And together with the official launch activities, a lot of Oracle and non-Oracle bloggers contributed helpful and informative blog articles to help your datacenter go to eleven. Here are some notable blog postings, sorted by category for your Solaris 11 blog-reading pleasure: Getting Started/Overview A lot of people speculated that the official launch of Solaris 11 would be on 11/11 (whatever way you want to turn it), but it actually happened two days earlier. Larry Wake himself offers 11 Reasons Why Oracle Solaris 11 11/11 Isn't Being Released on 11/11/11. Then, Larry goes on with a summary: Oracle Solaris 11: The First Cloud OS gives you a short and sweet rundown of what the major new features of Solaris 11 are. Jeff Victor has his own list of What's New in Oracle Solaris 11. A popular Solaris 11 meme is to write a blog post about 11 favourite features: Jim Laurent's 11 Reasons to Love Solaris 11, Darren Moffat's 11 Favourite Solaris 11 Features, Mike Gerdt's 11 of My Favourite Things! are just three examples of "11 Favourite Things..." type blog posts, I'm sure many more will follow... More official overview content for Solaris 11 is available from the Oracle Tech Network Solaris 11 Portal. Also, check out Rick Ramsey's blog post Solaris 11 Resources for System Administrators on the OTN Blog and his secret 5 Commands That Make Solaris Administration Easier post from the OTN Garage. (Automatic) Installation and the Image Packaging System (IPS) The brand new Image Packaging System (IPS) and the Automatic Installer (IPS), together with numerous other install/packaging/boot/patching features are among the most significant improvements in Solaris 11. But before installing, you may wonder whether Solaris 11 will support your particular set of hardware devices. Again, the OTN Garage comes to the rescue with Rick Ramsey's post How to Find Out Which Devices Are Supported By Solaris 11. Included is a useful guide to all the first steps to get your Solaris 11 system up and running. Tim Foster had a whole handful of blog posts lined up for the launch, teaching you everything you need to know about IPS but didn't dare to ask: The IPS System Repository, IPS Self-assembly - Part 1: Overlays and Part 2: Multiple Packages Delivering Configuration. Watch out for more IPS posts from Tim! If installing packages or upgrading your system from the net makes you uneasy, then you're not alone: Jim Laurent will tech you how Building a Solaris 11 Repository Without Network Connection will make your life easier. Many of you have already peeked into the future by installing Solaris 11 Express. If you're now wondering whether you can upgrade or whether a fresh install is necessary, then check out Alan Hargreaves's post Upgrading Solaris 11 Express b151a with support to Solaris 11. The trick is in upgrading your pkg(1M) first. Networking One of the first things to do after installing Solaris 11 (or any operating system for that matter), is to set it up for networking. Solaris 11 comes with the brand new "Network Auto-Magic" feature which can figure out everything by itself. For those cases where you want to exercise a little more control, Solaris 11 left a few people scratching their heads. Fortunately, Tschokko wrote up this cool blog post: Solaris 11 manual IPv4 & IPv6 configuration right after the launch ceremony. Thanks, Tschokko! And Milek points out a long awaited networking feature in Solaris 11 called Solaris 11 - hostmodel, which I know for a fact that many customers have looked forward to: How to "bind" a Solaris 11 system to a specific gateway for specific IP address it is using. Steffen Weiberle teaches us how to tune the Solaris 11 networking stack the proper way: ipadm(1M). No more fiddling with ndd(1M)! Check out his tutorial on Solaris 11 Network Tunables. And if you want to get even deeper into the networking stack, there's nothing better than DTrace. Alan Maguire teaches you in: DTracing TCP Congestion Control how to probe deeply into the Solaris 11 TCP/IP stack, the TCP congestion control part in particular. Don't miss his other DTrace and TCP related blog posts! DTrace And there we are: DTrace, the king of all observability tools. Long time DTrace veteran and co-author of The DTrace book*, Brendan Gregg blogged about Solaris 11 DTrace syscall provider changes. BTW, after you install Solaris 11, check out the DTrace toolkit which is installed by default in /usr/dtrace/DTT. It is chock full of handy DTrace scripts, many of which contributed by Brendan himself! Security Another big theme in Solaris 11, and one that is crucial for the success of any operating system in the Cloud is Security. Here are some notable posts in this category: Darren Moffat starts by showing us how to completely get rid of root: Completely Disabling Root Logins on Solaris 11. With no root user, there's one major entry point less to worry about. But that's only the start. In Immutable Zones on Encrypted ZFS, Darren shows us how to double the security of your services: First by locking them into the new Immutable Zones feature, then by encrypting their data using the new ZFS encryption feature. And if you're still missing sudo from your Linux days, Darren again has a solution: Password (PAM) caching for Solaris su - "a la sudo". If you're wondering how much compute power all this encryption will cost you, you're in luck: The Solaris X86 AESNI OpenSSL Engine will make sure you'll use your Intel's embedded crypto support to its fullest. And if you own a brand new SPARC T4 machine you're even luckier: It comes with its own SPARC T4 OpenSSL Engine. Dan Anderson's posts show how there really is now excuse not to encrypt any more... Developers Solaris 11 has a lot to offer to developers as well. Ali Bahrami has a series of blog posts that cover diverse developer topics: elffile: ELF Specific File Identification Utility, Using Stub Objects and The Stub Proto: Not Just For Stub Objects Anymore to name a few. BTW, if you're a developer and want to shape the future of Solaris 11, then Vijay Tatkar has a hint for you: Oracle (Sun Systems Group) is hiring! Desktop and Graphics Yes, Solaris 11 is a 100% server OS, but it can also offer a decent desktop environment, especially if you are a developer. Alan Coopersmith starts by discussing S11 X11: ye olde window system in today's new operating system, then Calum Benson shows us around What's new on the Solaris 11 Desktop. Even accessibility is a first-class citizen in the Solaris 11 user interface. Peter Korn celebrates: Accessible Oracle Solaris 11 - released! Performance Gone are the days of "Slowaris", when Solaris was among the few OSes that "did the right thing" while others cut corners just to win benchmarks. Today, Solaris continues doing the right thing, and it delivers the right performance at the same time. Need proof? Check out Brian's BestPerf blog with continuous updates from the benchmarking lab, including Recent Benchmarks Using Oracle Solaris 11! Send Me More Solaris 11 Launch Articles! These are just a few of the more interesting blog articles that came out around the Solaris 11 launch, I'm sure there are many more! Feel free to post a comment below if you find a particularly interesting blog post that hasn't been listed so far and share your enthusiasm for Solaris 11! *Affiliate link: Buy cool stuff and support this blog at no extra cost. We both win! var flattr_uid = '26528'; var flattr_tle = 'Solaris 11 Launch Blog Carnival Roundup'; var flattr_dsc = '<strong>Solaris 11 is here!</strong>And together with the official launch activities, a lot of Oracle and non-Oracle bloggers contributed helpful and informative blog articles to help your datacenter <a href="http://en.wikipedia.org/wiki/Up_to_eleven">go to eleven</a>.Here are some notable blog postings, sorted by category for your Solaris 11 blog-reading pleasure:'; var flattr_tag = 'blogging,digest,Oracle,Solaris,solaris,solaris 11'; var flattr_cat = 'text'; var flattr_url = 'http://constantin.glez.de/blog/2011/11/solaris-11-launch-blog-carnival-roundup'; var flattr_lng = 'en_GB'

    Read the article

  • An XEvent a Day (12 of 31) – Using the Extended Events SSMS Addin

    - by Jonathan Kehayias
    The lack of SSMS support for Extended Events, coupled with the fact that a number of the existing Events in SQL Trace were not implemented in SQL Server 2008, has no doubt been a key factor in its slow adoption rate. Since the release of SQL Server Denali CTP1, I have already seen a number of blog posts that talk about the introduction of Extended Events in SQL Server, because there is now a stub for it inside of SSMS. Don’t get excited yet, the functionality in CTP1 is very limited at this point,...(read more)

    Read the article

  • TechEd 2012 - day 3

    - by Stefan Barrett
    The content has got more useful for me as a developer, and I've now seen 2 things which I think will make a big difference: Fake in vs2012 - allows me to stub or fake out libraries making unit testing easier/possible. C++ AMP & auto - auto might get me to start using c++ again (it makes code like for each much nicer/easier to write), while AMP is something I want to play with (moves the processing onto the GPU) The food got a little better, while there was less sign of the snacks.

    Read the article

  • Ubuntu 12.10 Wine Crash Error Help

    - by Hao
    I'm trying to get wine to work for Hawken. I used winetricks and installed all the necessary components. Wine works fine with other games I have installed but when I try to run Hawken it crashes while loading with the following error: fixme:iphlpapi:CancelIPChangeNotify (overlapped 0xf2afb8): stub I'm new to Ubuntu so I have no idea how to fix this. Any help would be much appreciated. *Update: I've done some backtracking and it seems that this error is caused by the launcher not wine itself.

    Read the article

  • Problems using HibernateTemplate: java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session;

    - by user2104160
    I am quite new in Spring world and I am going crazy trying to integrate Hibernate in Spring application using HibernateTemplate abstract support class I have the following class to persist on database table: package org.andrea.myexample.HibernateOnSpring.entity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="person") public class Person { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int pid; private String firstname; private String lastname; public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } } Next to it I have create an interface named PersonDAO in wich I only define my CRUD method. So I have implement this interface by a class named PersonDAOImpl that also extend the Spring abstract class HibernateTemplate: package org.andrea.myexample.HibernateOnSpring.dao; import java.util.List; import org.andrea.myexample.HibernateOnSpring.entity.Person; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class PersonDAOImpl extends HibernateDaoSupport implements PersonDAO{ public void addPerson(Person p) { getHibernateTemplate().saveOrUpdate(p); } public Person getById(int id) { // TODO Auto-generated method stub return null; } public List<Person> getPersonsList() { // TODO Auto-generated method stub return null; } public void delete(int id) { // TODO Auto-generated method stub } public void update(Person person) { // TODO Auto-generated method stub } } (at the moment I am trying to implement only the addPerson() method) Then I have create a main class to test the operation of insert a new object into the database table: package org.andrea.myexample.HibernateOnSpring; import org.andrea.myexample.HibernateOnSpring.dao.PersonDAO; import org.andrea.myexample.HibernateOnSpring.entity.Person; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); System.out.println("Contesto recuperato: " + context); Person persona1 = new Person(); persona1.setFirstname("Pippo"); persona1.setLastname("Blabla"); System.out.println("Creato persona1: " + persona1); PersonDAO dao = (PersonDAO) context.getBean("personDAOImpl"); System.out.println("Creato dao object: " + dao); dao.addPerson(persona1); System.out.println("persona1 salvata nel database"); } } As you can see the PersonDAOImpl class extends HibernateTemplate so I think that it have to contain the operation of setting of the sessionFactory... The problem is that when I try to run this MainApp class I obtain the following exception: Exception in thread "main" java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session; at org.springframework.orm.hibernate3.SessionFactoryUtils.doGetSession(SessionFactoryUtils.java:323) at org.springframework.orm.hibernate3.SessionFactoryUtils.getSession(SessionFactoryUtils.java:235) at org.springframework.orm.hibernate3.HibernateTemplate.getSession(HibernateTemplate.java:457) at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:392) at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) at org.springframework.orm.hibernate3.HibernateTemplate.saveOrUpdate(HibernateTemplate.java:737) at org.andrea.myexample.HibernateOnSpring.dao.PersonDAOImpl.addPerson(PersonDAOImpl.java:12) at org.andrea.myexample.HibernateOnSpring.MainApp.main(MainApp.java:26) Why I have this problem? how can I solve it? To be complete I also insert my pom.xml containing my dependencies list: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.andrea.myexample</groupId> <artifactId>HibernateOnSpring</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>HibernateOnSpring</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <!-- Dipendenze di Spring Framework --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>3.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>3.2.1.RELEASE</version> </dependency> <dependency> <!-- Usata da Hibernate 4 per LocalSessionFactoryBean --> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.2.0.RELEASE</version> </dependency> <!-- Dipendenze per AOP --> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency> <!-- Dipendenze per Persistence Managment --> <dependency> <!-- Apache BasicDataSource --> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <!-- MySQL database driver --> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.23</version> </dependency> <dependency> <!-- Hibernate --> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.1.9.Final</version> </dependency> </dependencies> </project>

    Read the article

  • Android: restful API service

    - by Martyn
    Hey, I'm looking to make a service which I can use to make calls to a web based rest api. I've spent a couple of days looking through stackoverflow.com, reading books and looking at articles whilst playing about with some code and I can't get anything which I'm happy with. Basically I want to start a service on app init then I want to be able to ask that service to request a url and return the results. In the meantime I want to be able to display a progress window or something similar. I've created a service currently which uses IDL, I've read somewhere that you only really need this for cross app communication, so think these needs stripping out but unsure how to do callbacks without it. Also when I hit the post(Config.getURL("login"), values) the app seems to pause for a while (seems weird - thought the idea behind a service was that it runs on a different thread!) Currently I have a service with post and get http methods inside, a couple of AIDL files (for two way communication), a ServiceManager which deals with starting, stopping, binding etc to the service and I'm dynamically creating a Handler with specific code for the callbacks as needed. I don't want anyone to give me a complete code base to work on, but some pointers would be greatly appreciated; even if it's to say I'm doing it completely wrong. I'm pretty new to Android and Java dev so if there are any blindingly obvious mistakes here - please don't think I'm a rubbish developer, I'm just wet behind the ears and would appreciate being told exactly where I'm going wrong. Anyway, code in (mostly) full (really didn't want to put this much code here, but I don't know where I'm going wrong - apologies in advance): public class RestfulAPIService extends Service { final RemoteCallbackList<IRemoteServiceCallback> mCallbacks = new RemoteCallbackList<IRemoteServiceCallback>(); public void onStart(Intent intent, int startId) { super.onStart(intent, startId); } public IBinder onBind(Intent intent) { return binder; } public void onCreate() { super.onCreate(); } public void onDestroy() { super.onDestroy(); mCallbacks.kill(); } private final IRestfulService.Stub binder = new IRestfulService.Stub() { public void doLogin(String username, String password) { Message msg = new Message(); Bundle data = new Bundle(); HashMap<String, String> values = new HashMap<String, String>(); values.put("username", username); values.put("password", password); String result = post(Config.getURL("login"), values); data.putString("response", result); msg.setData(data); msg.what = Config.ACTION_LOGIN; mHandler.sendMessage(msg); } public void registerCallback(IRemoteServiceCallback cb) { if (cb != null) mCallbacks.register(cb); } }; private final Handler mHandler = new Handler() { public void handleMessage(Message msg) { // Broadcast to all clients the new value. final int N = mCallbacks.beginBroadcast(); for (int i = 0; i < N; i++) { try { switch (msg.what) { case Config.ACTION_LOGIN: mCallbacks.getBroadcastItem(i).userLogIn( msg.getData().getString("response")); break; default: super.handleMessage(msg); return; } } catch (RemoteException e) { } } mCallbacks.finishBroadcast(); } public String post(String url, HashMap<String, String> namePairs) {...} public String get(String url) {...} }; A couple of AIDL files: package com.something.android oneway interface IRemoteServiceCallback { void userLogIn(String result); } and package com.something.android import com.something.android.IRemoteServiceCallback; interface IRestfulService { void doLogin(in String username, in String password); void registerCallback(IRemoteServiceCallback cb); } and the service manager: public class ServiceManager { final RemoteCallbackList<IRemoteServiceCallback> mCallbacks = new RemoteCallbackList<IRemoteServiceCallback>(); public IRestfulService restfulService; private RestfulServiceConnection conn; private boolean started = false; private Context context; public ServiceManager(Context context) { this.context = context; } public void startService() { if (started) { Toast.makeText(context, "Service already started", Toast.LENGTH_SHORT).show(); } else { Intent i = new Intent(); i.setClassName("com.something.android", "com.something.android.RestfulAPIService"); context.startService(i); started = true; } } public void stopService() { if (!started) { Toast.makeText(context, "Service not yet started", Toast.LENGTH_SHORT).show(); } else { Intent i = new Intent(); i.setClassName("com.something.android", "com.something.android.RestfulAPIService"); context.stopService(i); started = false; } } public void bindService() { if (conn == null) { conn = new RestfulServiceConnection(); Intent i = new Intent(); i.setClassName("com.something.android", "com.something.android.RestfulAPIService"); context.bindService(i, conn, Context.BIND_AUTO_CREATE); } else { Toast.makeText(context, "Cannot bind - service already bound", Toast.LENGTH_SHORT).show(); } } protected void destroy() { releaseService(); } private void releaseService() { if (conn != null) { context.unbindService(conn); conn = null; Log.d(LOG_TAG, "unbindService()"); } else { Toast.makeText(context, "Cannot unbind - service not bound", Toast.LENGTH_SHORT).show(); } } class RestfulServiceConnection implements ServiceConnection { public void onServiceConnected(ComponentName className, IBinder boundService) { restfulService = IRestfulService.Stub.asInterface((IBinder) boundService); try { restfulService.registerCallback(mCallback); } catch (RemoteException e) {} } public void onServiceDisconnected(ComponentName className) { restfulService = null; } }; private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() { public void userLogIn(String result) throws RemoteException { mHandler.sendMessage(mHandler.obtainMessage(Config.ACTION_LOGIN, result)); } }; private Handler mHandler; public void setHandler(Handler handler) { mHandler = handler; } } Service init and bind: // this I'm calling on app onCreate servicemanager = new ServiceManager(this); servicemanager.startService(); servicemanager.bindService(); application = (ApplicationState)this.getApplication(); application.setServiceManager(servicemanager); service function call: // this lot i'm calling as required - in this example for login progressDialog = new ProgressDialog(Login.this); progressDialog.setMessage("Logging you in..."); progressDialog.show(); application = (ApplicationState) getApplication(); servicemanager = application.getServiceManager(); servicemanager.setHandler(mHandler); try { servicemanager.restfulService.doLogin(args[0], args[1]); } catch (RemoteException e) { e.printStackTrace(); } ...later in the same file... Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case Config.ACTION_LOGIN: if (progressDialog.isShowing()) { progressDialog.dismiss(); } try { ...process login results... } } catch (JSONException e) { Log.e("JSON", "There was an error parsing the JSON", e); } break; default: super.handleMessage(msg); } } }; Any and all help is greatly appreciated and I'll even buy you a coffee or a beer if you fancy :D Martyn

    Read the article

  • Get the current location of the Gps? Showing the default one

    - by Gagandeep
    Need help Urgent!!!!! Did changes with help but still unsuccessful... I have to request location updates, but I am unsuccessful in implementing that... i modified the code but need help so that i can see the current location. PLEASE look through my code and help please.. I am learning this and new to this concept and android.. any help would be appreciated here is my code: package com.GoogleMaps; import java.util.List; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.drawable.Drawable; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.widget.Toast; public class MapsActivity extends MapActivity { /** Called when the activity is first created. */ private MapView mapView; private LocationManager lm; private LocationListener ll; private MapController mc; GeoPoint p = null; Drawable defaultMarker = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mapView = (MapView)findViewById(R.id.mapview); //show zoom in/out buttons mapView.setBuiltInZoomControls(true); //Standard view of the map(map/sat) mapView.setSatellite(false); // get zoom tool mapView.setBuiltInZoomControls(true); //get controller of the map for zooming in/out mc = mapView.getController(); // Zoom Level mc.setZoom(18); lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); ll = new MyLocationListener(); lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll); //Get the current location in start-up lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); ll = new MyLocationListener(); lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll); //Get the current location in start-up if (lm.getLastKnownLocation(LocationManager.GPS_PROVIDER) != null){ GeoPoint p = new GeoPoint( (int)(lm.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLatitude()*1000000), (int)(lm.getLastKnownLocation(LocationManager.GPS_PROVIDER).getLongitude()*1000000)); mc.animateTo(p); } MyLocationOverlay myLocationOverlay = new MyLocationOverlay(); List<Overlay> list = mapView.getOverlays(); list.add(myLocationOverlay); } protected class MyLocationOverlay extends com.google.android.maps.Overlay { @Override public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) { Paint paint = new Paint(); super.draw(canvas, mapView, shadow); GeoPoint p = null; // Converts lat/lng-Point to OUR coordinates on the screen. Point myScreenCoords = new Point(); mapView.getProjection().toPixels(p, myScreenCoords); paint.setStrokeWidth(1); paint.setARGB(255, 255, 255, 255); paint.setStyle(Paint.Style.STROKE); Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint); canvas.drawText("I am here...", myScreenCoords.x, myScreenCoords.y, paint); return true; } } private class MyLocationListener implements LocationListener{ public void onLocationChanged(Location argLocation) { // TODO Auto-generated method stub p = new GeoPoint((int)(argLocation.getLatitude()*1000000), (int)(argLocation.getLongitude()*1000000)); Toast.makeText(getBaseContext(), "New location latitude [" +argLocation.getLatitude() + "] longitude [" + argLocation.getLongitude()+"]", Toast.LENGTH_SHORT).show(); mc.animateTo(p); mapView.invalidate(); // call this so UI of map was updated } 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 } } protected boolean isRouteDisplayed() { return false; } } catlog: 11-29 17:40:42.699: D/dalvikvm(371): GC_FOR_MALLOC freed 6074 objects / 369952 bytes in 74ms 11-29 17:40:42.970: I/MapActivity(371): Handling network change notification:CONNECTED 11-29 17:40:42.980: E/MapActivity(371): Couldn't get connection factory client 11-29 17:40:43.190: D/AndroidRuntime(371): Shutting down VM 11-29 17:40:43.190: W/dalvikvm(371): threadid=1: thread exiting with uncaught exception (group=0x4001d800) 11-29 17:40:43.280: E/AndroidRuntime(371): FATAL EXCEPTION: main 11-29 17:40:43.280: E/AndroidRuntime(371): java.lang.NullPointerException 11-29 17:40:43.280: E/AndroidRuntime(371): at com.google.android.maps.PixelConverter.toPixels(PixelConverter.java:71) 11-29 17:40:43.280: E/AndroidRuntime(371): at com.google.android.maps.PixelConverter.toPixels(PixelConverter.java:61) 11-29 17:40:43.280: E/AndroidRuntime(371): at com.GoogleMaps.MapsActivity$MyLocationOverlay.draw(MapsActivity.java:106) 11-29 17:40:43.280: E/AndroidRuntime(371): at com.google.android.maps.OverlayBundle.draw(OverlayBundle.java:42) 11-29 17:40:43.280: E/AndroidRuntime(371): at com.google.android.maps.MapView.onDraw(MapView.java:494) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.View.draw(View.java:6740) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.drawChild(ViewGroup.java:1640) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.drawChild(ViewGroup.java:1638) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.View.draw(View.java:6743) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.widget.FrameLayout.draw(FrameLayout.java:352) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.drawChild(ViewGroup.java:1640) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.drawChild(ViewGroup.java:1638) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.View.draw(View.java:6743) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.widget.FrameLayout.draw(FrameLayout.java:352) 11-29 17:40:43.280: E/AndroidRuntime(371): at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1842) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewRoot.draw(ViewRoot.java:1407) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewRoot.performTraversals(ViewRoot.java:1163) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.view.ViewRoot.handleMessage(ViewRoot.java:1727) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.os.Handler.dispatchMessage(Handler.java:99) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.os.Looper.loop(Looper.java:123) 11-29 17:40:43.280: E/AndroidRuntime(371): at android.app.ActivityThread.main(ActivityThread.java:4627) 11-29 17:40:43.280: E/AndroidRuntime(371): at java.lang.reflect.Method.invokeNative(Native Method) 11-29 17:40:43.280: E/AndroidRuntime(371): at java.lang.reflect.Method.invoke(Method.java:521) 11-29 17:40:43.280: E/AndroidRuntime(371): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 11-29 17:40:43.280: E/AndroidRuntime(371): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 11-29 17:40:43.280: E/AndroidRuntime(371): at dalvik.system.NativeStart.main(Native Method) 11-29 17:40:45.779: D/dalvikvm(371): GC_FOR_MALLOC freed 5970 objects / 506624 bytes in 1179ms 11-29 17:40:45.779: I/dalvikvm-heap(371): Grow heap (frag case) to 3.147MB for 17858-byte allocation 11-29 17:40:45.870: D/dalvikvm(371): GC_FOR_MALLOC freed 56 objects / 2304 bytes in 92ms 11-29 17:40:45.960: D/dalvikvm(371): GC_EXPLICIT freed 3459 objects / 196432 bytes in 74ms 11-29 17:40:48.310: D/dalvikvm(371): GC_EXPLICIT freed 116 objects / 41448 bytes in 68ms 11-29 17:40:49.540: I/Process(371): Sending signal. PID: 371 SIG: 9

    Read the article

  • Only error showing is null, rss feed reader not working

    - by Callum
    I have been following a tutorial which is showing me how to create an rssfeed reader, I come to the end of the tutorial; and the feed is not displaying in the listView. So I am looking for errors in logCat, but the only one I can find is one just saying 'null', which is not helpful at all. Can anyone spot a potential problem with the code I have written? Thanks. DirectRSS(main class): package com.example.rssapplication; import java.util.List; import android.app.ListActivity; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; public class DirectRSS extends ListActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.directrss); //Set to portrait, so that every time the view changes; it does not run the DB query again... setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); try{ RssReader1 rssReader = new RssReader1("http://www.skysports.com/rss/0,20514,11661,00.xml"); ListView list = (ListView)findViewById(R.id.list); ArrayAdapter<RssItem1> adapter = new ArrayAdapter<RssItem1>(this, android.R.layout.simple_list_item_1); list.setAdapter(adapter); list.setOnItemClickListener(new ListListener1(rssReader.getItems(),this)); }catch(Exception e) { String err = (e.getMessage()==null)?"SD Card failed": e.getMessage(); Log.e("sdcard-err2:",err + " " + e.getMessage()); // Log.e("Error", e.getMessage()); Log.e("LOGCAT", "" + e.getMessage()); } } } ListListener1: package com.example.rssapplication; import java.util.List; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; public class ListListener1 implements OnItemClickListener{ List<RssItem1> listItems; Activity activity; public ListListener1(List<RssItem1> listItems, Activity activity) { this.listItems = listItems; this.activity = activity; } @Override public void onItemClick(AdapterView<?> parent, View view, int pos, long id) { // TODO Auto-generated method stub Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(listItems.get(pos).getLink())); activity.startActivity(i); } } RssItem1: package com.example.rssapplication; public class RssItem1 { private String title; private String link; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } } RssParseHandler1: package com.example.rssapplication; import java.util.ArrayList; import java.util.List; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class RssParseHandler1 extends DefaultHandler{ private List<RssItem1> rssItems; private RssItem1 currentItem; private boolean parsingTitle; private boolean parsingLink; public RssParseHandler1(){ rssItems = new ArrayList<RssItem1>(); } public List<RssItem1> getItems(){ return rssItems; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if("item".equals(qName)){ currentItem = new RssItem1(); } else if("title".equals(qName)){ parsingTitle = true; } else if("link".equals(qName)){ parsingLink = true; } // TODO Auto-generated method stub super.startElement(uri, localName, qName, attributes); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { if("item".equals(qName)){ rssItems.add(currentItem); currentItem = null; } else if("title".equals(qName)){ parsingTitle = false; } else if("link".equals(qName)){ parsingLink = false; } // TODO Auto-generated method stub super.endElement(uri, localName, qName); } @Override public void characters(char[] ch, int start, int length) throws SAXException { if(parsingTitle) { if(currentItem!=null) { currentItem.setTitle(new String(ch,start,length)); } } else if(parsingLink) { if(currentItem!=null) { currentItem.setLink(new String(ch,start,length)); parsingLink = false; } } // TODO Auto-generated method stub super.characters(ch, start, length); } } RssReader1: package com.example.rssapplication; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; public class RssReader1 { private String rssUrl; public RssReader1(String rssUrl) { this.rssUrl = rssUrl; } public List<RssItem1> getItems() throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); RssParseHandler1 handler = new RssParseHandler1(); saxParser.parse(rssUrl, handler); return handler.getItems(); } } Here is the logCat also: 08-25 11:13:20.803: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:20.803: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:20.803: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:20.813: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:20.813: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:20.813: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:20.813: W/ApplicationPackageManager(26291): getCSCPackageItemText() 08-25 11:13:20.843: D/AbsListView(26291): Get MotionRecognitionManager 08-25 11:13:20.843: E/sdcard-err2:(26291): SD Card failed null 08-25 11:13:20.843: E/LOGCAT(26291): null 08-25 11:13:20.843: D/AbsListView(26291): onVisibilityChanged() is called, visibility : 4 08-25 11:13:20.843: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:20.873: D/AbsListView(26291): onVisibilityChanged() is called, visibility : 0 08-25 11:13:20.883: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:20.903: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:20.933: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:20.963: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:20.973: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:21.323: D/AbsListView(26291): onVisibilityChanged() is called, visibility : 4 08-25 11:13:21.323: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:21.323: D/AbsListView(26291): onVisibilityChanged() is called, visibility : 4 08-25 11:13:21.323: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:21.323: D/AbsListView(26291): onVisibilityChanged() is called, visibility : 4 08-25 11:13:21.323: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:21.323: D/AbsListView(26291): onVisibilityChanged() is called, visibility : 4 08-25 11:13:21.323: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:21.323: D/AbsListView(26291): onVisibilityChanged() is called, visibility : 4 08-25 11:13:21.323: D/AbsListView(26291): unregisterIRListener() is called 08-25 11:13:21.333: D/AbsListView(26291): onVisibilityChanged() is called, visibility : 4 08-25 11:13:21.333: D/AbsListView(26291): unregisterIRListener() is called

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >