Search Results

Search found 335 results on 14 pages for 'httpclient'.

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

  • java.lang.OutOfMemoryError: bitmap size exceeds VM budget ?

    - by UMMA
    friends, i am using following code to display bitmap on screen and having next and previous buttons to change images. and getting out of memory error New Code HttpGet httpRequest = null; try { httpRequest = new HttpGet(mImage_URL[val]); } catch (Exception e) { return 0; } HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); Bitmap bm; HttpEntity entity = response.getEntity(); BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); InputStream is = bufHttpEntity.getContent(); try { bm = BitmapFactory.decodeStream(is); }catch(Exception ex) { } is.close(); Old Code URL aURL = new URL(mImage_URL[val]); URLConnection conn = aURL.openConnection(); conn.connect(); InputStream is = null; try { is= conn.getInputStream(); }catch(IOException e) { } BufferedInputStream bis = new BufferedInputStream(is); bm = BitmapFactory.decodeStream(bis); bis.close(); is.close(); img.setImageBitmap(bm); and it was giving me error decoder-decode return false. on images of size bigger than 400kb. so after googling i got new code as answer the old code was not giving me out of memory error on those images but decoder-decode return false, so i choosed new code. any one guide me what is the solution and which is the best approach to display live images?

    Read the article

  • Production settings file for log4j?

    - by James
    Here is my current log4j settings file. Are these settings ideal for production use or is there something I should remove/tweak or change? I ask because I was getting all my threads being hung due to log4j blocking. I checked my open file descriptors I was only using 113. # ***** Set root logger level to WARN and its two appenders to stdout and R. log4j.rootLogger=warn, stdout, R # ***** stdout is set to be a ConsoleAppender. log4j.appender.stdout=org.apache.log4j.ConsoleAppender # ***** stdout uses PatternLayout. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout # ***** Pattern to output the caller's file name and line number. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n # ***** R is set to be a RollingFileAppender. log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.R.File=logs/myapp.log # ***** Max file size is set to 100KB log4j.appender.R.MaxFileSize=102400KB # ***** Keep one backup file log4j.appender.R.MaxBackupIndex=5 # ***** R uses PatternLayout. log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%p %t %d %c - %m%n #set httpclient debug levels log4j.logger.org.apache.component=ERROR,stdout log4j.logger.httpclient.wire=ERROR,stdout log4j.logger.org.apache.commons.httpclient=ERROR,stdout log4j.logger.org.apache.http.client.protocol=ERROR,stdout UPDATE*** Adding thread dump sample from all my threads (100) "pool-1-thread-5" - Thread t@25 java.lang.Thread.State: BLOCKED on org.apache.log4j.spi.RootLogger@1d45a585 owned by: pool-1-thread-35 at org.apache.log4j.Category.callAppenders(Category.java:201) at org.apache.log4j.Category.forcedLog(Category.java:388) at org.apache.log4j.Category.error(Category.java:302)

    Read the article

  • Android HttpPost: how to get the result

    - by Sumit M Asok
    I have been trying long to send an HttpPost request and retrieve response but even though I was able to make a connection I don't yet get how to get the string message which is returned by the request-response HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.myurl.com/app/page.php"); // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5); nameValuePairs.add(new BasicNameValuePair("type", "20")); nameValuePairs.add(new BasicNameValuePair("mob", "919895865899")); nameValuePairs.add(new BasicNameValuePair("pack", "0")); nameValuePairs.add(new BasicNameValuePair("exchk", "1")); try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); Log.d("myapp", "works till here. 2"); try { HttpResponse response = httpclient.execute(httppost); Log.d("myapp", "response " + response.getEntity()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } I'm sorry, I sound very naive because I'm new to java. Please help me.

    Read the article

  • Apache Axis2 1.5.1 and NTLM Authentication

    - by arcticpenguin
    I've browsed all of the discussions here on StackOverflow regarding NTLM and Java, and I can't seem to find the answer. I'll try and be much more specific. Here's some code that returns a client stub that (I hope) is configured for NTLM authentication: ServiceStub getService() { try { ServiceStub stub = new ServiceStub( "http://myserver/some/path/to/webservices.asmx"); // this service is hosted on IIS List<String> ntlmPreferences = new ArrayList<String>(1); ntlmPreferences.add(HttpTransportProperties.Authenticator.NTLM); HttpTransportProperties.Authenticator ntlmAuthenticator = new HttpTransportProperties.Authenticator(); ntlmAuthenticator.setPreemptiveAuthentication(true); ntlmAuthenticator.setAuthSchemes(ntlmPreferences); ntlmAuthenticator.setUsername("me"); ntlmAuthenticator.setHost("localhost"); ntlmAuthenticator.setDomain("mydomain"); Options options = stub._getServiceClient().getOptions(); options.setProperty(HTTPConstants.AUTHENTICATE, ntlmAuthenticator); options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, "true"); stub._getServiceClient().setOptions(options); return stub; } catch (AxisFault e) { e.printStackTrace(); } return null; } This returns a valid SerivceStub object. When I try to invoke a call on the stub, I see the following in my log: Jun 9, 2010 12:12:22 PM org.apache.commons.httpclient.auth.AuthChallengeProcessor selectAuthScheme INFO: NTLM authentication scheme selected Jun 9, 2010 12:12:22 PM org.apache.commons.httpclient.HttpMethodDirector authenticate SEVERE: Credentials cannot be used for NTLM authentication: org.apache.commons.httpclient.UsernamePasswordCredentials Does anyone have a solution to this issue?

    Read the article

  • android compile error: could not reserve enough space for object heap

    - by moonlightcheese
    I'm getting this error during compilation: Error occurred during initialization of VM Could not create the Java virtual machine. Could not reserve enough space for object heap What's worse, the error occurs intermittently. Sometimes it happens, sometimes it doesn't. It seems to be dependent on the amount of code in the application. If I get rid of some variables or drop some imported libraries, it will compile. Then when I add more to it, I get the error again. I've included the following sources into the application in the [project_root]/src/ directory: org.apache.httpclient (I've stripped all references to log4j from the sources, so don't need it) org.apache.codec (as a dependency) org.apache.httpcore (dependency of httpclient) and my own activity code consisting of nothing more than an instance of HttpClient. I know this has something to do with the amount of memory necessary during compile time or some compiler options, and I'm not really stressing my system while i'm coding. I've got 2GB of memory on this Core Duo laptop and windows reports only 860MB page file usage (haven't used any other memory tools. I should have plenty of memory and processing power for this... and I'm only compiling some common http libs... total of 406 source files. What gives? Android API Level: 5 Android SDK rel 5 JDK version: 1.6.0_12

    Read the article

  • Fatal error: Uncaught exception 'Zend_Gdata_App_HttpException' with message 'Expected response code 200, got 401'

    - by Peak Reconstruction Wavelength
    I am using a php-script that has been working for years, but suddenly it aborts with Fatal error: Uncaught exception 'Zend_Gdata_App_HttpException' with message 'Expected response code 200, got 401' NoLinkedYouTubeAccount Error 401 It starts like this <?php function anmelden_yt($name,$passwort) { $yt_source = 'known'; $yt_api_key = 'key'; $yt = null; $authenticationURL= 'https://www.google.com/accounts/ClientLogin'; $httpClient = Zend_Gdata_ClientLogin::getHttpClient( $username = $name, $password = $passwort, $service = 'youtube', $client = null, $source = $yt_source, // a short string identifying your application $loginToken = null, $loginCaptcha = null, $authenticationURL); abschnitt("Login"); return new Zend_Gdata_YouTube($httpClient, $yt_source, NULL, $yt_api_key); } require_once("Zend/Gdata/ClientLogin.php"); require_once("Zend/Gdata/HttpClient.php"); require_once("Zend/Gdata/YouTube.php"); require_once("Zend/Gdata/App/MediaFileSource.php"); require_once("Zend/Gdata/App/HttpException.php"); require_once('Zend/Uri/Http.php'); require_once 'Zend/Loader.php'; Zend_Loader::loadClass('Zend_Gdata_YouTube'); Zend_Loader::loadClass('Zend_Gdata_AuthSub'); Zend_Loader::loadClass('Zend_Gdata_ClientLogin'); $yt = anmelden_yt($name,$pass); $videoFeed = $yt->getUserUploads('Google'); sleep(0.5); @ob_flush(); @flush(); ?> What could be the reason for this? ..................................................................................................

    Read the article

  • Android: Determine when app is being finalized

    - by Matt
    Hi all, I posted a question yesterday about determining when an app is being finalized vs destroyed for screen orientation change. Thanks to the answers I received I was able to resolve my problem with the screen orientation change. However, I am still running into a roadblock. This app I am working on logs into a website with an HttpClient. As long as the app remains in memory the HttpClient will retain the cookies from logging in. However, once it is killed, it would need to log in again. My question: How can I determine when the app is being killed from memory so I can set a boolean to false telling the app it has been removed from memory so the next time it starts it will read this and determine is must log in again? Or is it possible to serialize an HttpClient and put that in the savedInstanceState bundle? May extract the cookies from the client and put those in the savedInstanceState bundle? Is there something I'm completely missing here maybe? Any help or a point in the right direction is greatly appreciated because this one has me stumped. Thank you!

    Read the article

  • How to send a JSONObject to a REST service?

    - by Sebi
    Retrieving data from the REST Server works well, but if I want to post an object it doesn't work: public static void postJSONObject(int store_type, FavoriteItem favorite, String token, String objectName) { String url = ""; switch(store_type) { case STORE_PROJECT: url = URL_STORE_PROJECT_PART1 + token + URL_STORE_PROJECT_PART2; //data = favorite.getAsJSONObject(); break; } HttpClient httpClient = new DefaultHttpClient(); HttpPost postMethod = new HttpPost(url); try { HttpEntity entity = new StringEntity("{\"ID\":0,\"Name\":\"Mein Projekt10\"}"); postMethod.setEntity(entity); HttpResponse response = httpClient.execute(postMethod); Log.i("JSONStore", "Post request, to URL: " + url); System.out.println("Status code: " + response.getStatusLine().getStatusCode()); } catch (ClientProtocolException e) { I always get a 400 Error Code. Does anybody know whats wrong? I have working C# code, but I can't convert: System.Net.WebRequest wr = System.Net.HttpWebRequest.Create("http://localhost:51273/WSUser.svc/pak3omxtEuLrzHSUSbQP/project"); wr.Method = "POST"; string data = "{\"ID\":1,\"Name\":\"Mein Projekt\"}"; byte [] d = UTF8Encoding.UTF8.GetBytes(data); wr.ContentLength = d.Length; wr.ContentType = "application/json"; wr.GetRequestStream().Write(d, 0, d.Length); System.Net.WebResponse wresp = wr.GetResponse(); System.IO.StreamReader sr = new System.IO.StreamReader(wresp.GetResponseStream()); string line = sr.ReadToEnd();

    Read the article

  • why am I stuck on "Initiating update" when deploying to google

    - by michelle
    I've have not had any trouble deploying through eclipse until now. I'm guessing it might have to do with all the stuff I've added today a folder of .pdf and .tex files (in war/web-inf directory) a bit of JDO stuff and a servlet that reads the files in the directory and indexes them into the JDO Is there any way to find out what exactly is the problem? I currently get stuck at "Initiating update" and the stack trace say "ConnectionReset" Any helkp of imput will be appreciated, I really need to deploy this today, thanks! here's the deploy trace: Unable to update: java.net.SocketException: Connection reset at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection$6.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at sun.net.www.protocol.http.HttpURLConnection.getChainedException(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at java.net.HttpURLConnection.getResponseCode(Unknown Source) at com.google.appengine.tools.admin.ServerConnection.getAuthCookie(ServerConnection.java:315) at com.google.appengine.tools.admin.ServerConnection.authenticate(ServerConnection.java:219) at com.google.appengine.tools.admin.ServerConnection.send(ServerConnection.java:145) at com.google.appengine.tools.admin.ServerConnection.post(ServerConnection.java:81) at com.google.appengine.tools.admin.AppVersionUpload.send(AppVersionUpload.java:427) at com.google.appengine.tools.admin.AppVersionUpload.beginTransaction(AppVersionUpload.java:241) at com.google.appengine.tools.admin.AppVersionUpload.doUpload(AppVersionUpload.java:98) at com.google.appengine.tools.admin.AppAdminImpl.update(AppAdminImpl.java:56) at com.google.appengine.eclipse.core.proxy.AppEngineBridgeImpl.deploy(AppEngineBridgeImpl.java:271) at com.google.appengine.eclipse.core.deploy.DeployProjectJob.runInWorkspace(DeployProjectJob.java:148) at org.eclipse.core.internal.resources.InternalWorkspaceJob.run(InternalWorkspaceJob.java:38) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) Caused by: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(Unknown Source) at java.io.BufferedInputStream.fill(Unknown Source) at java.io.BufferedInputStream.read1(Unknown Source) at java.io.BufferedInputStream.read(Unknown Source) at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source) at sun.net.www.http.HttpClient.parseHTTP(Unknown Source) at sun.net.www.http.HttpClient.parseHTTP(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getHeaderFieldKey(Unknown Source) at com.google.appengine.tools.util.ClientCookieManager.readCookies(ClientCookieManager.java:123) at com.google.appengine.tools.admin.ServerConnection.connect(ServerConnection.java:340) at com.google.appengine.tools.admin.ServerConnection.getAuthCookie(ServerConnection.java:314) ... 11 more

    Read the article

  • Android - How can I upload a txt file to a website?

    - by Donal Rafferty
    I want to upload a txt file to a website, I'll admit I haven't looked into it in any great detail but I have looked at a few examples and would like more experienced opinions on whether I'm going in the right direction. Here is what I have so far: DefaultHttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); private String ret; HttpResponse response = null; HttpPost httpPost = null; public String postPage(String url, String data, boolean returnAddr) { ret = null; httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109); httpPost = new HttpPost(url); response = null; StringEntity tmp = null; try { tmp = new StringEntity(data,"UTF-8"); } catch (UnsupportedEncodingException e) { System.out.println("HTTPHelp : UnsupportedEncodingException : "+e); } httpPost.setEntity(tmp); try { response = httpClient.execute(httpPost,localContext); } catch (ClientProtocolException e) { System.out.println("HTTPHelp : ClientProtocolException : "+e); } catch (IOException e) { System.out.println("HTTPHelp : IOException : "+e); } ret = response.getStatusLine().toString(); return ret; } And I call it as follows: postPage("http://www.testwebsite.com", "data/data/com.testxmlpost.xml/files/logging.txt", true)); I want to be able to upload a file from the device to a website. But when trying this way I get the following response back. HTTP/1.1 405 Method Not Allowed Am I trying the correct way or should I be doing it another way?

    Read the article

  • Android: sending xml as document object, POST method

    - by juro
    i am new at programming and i need some help with that please =/ web service is already written but not by me. so all i have to do is send xml as document object by post method through web service. my code: public class send extends application { @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://app.local/test/"); try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element rootElement = document.createElement("packet"); rootElement.setAttribute("version", "1.2"); document.appendChild(rootElement); Element em = document.createElement("imei"); em.appendChild(document.createTextNode("000000000000000")); rootElement.appendChild(em); em = document.createElement("username"); em.appendChild(document.createTextNode("5555")); rootElement.appendChild(em); HttpResponse response = httpclient.execute(httppost); } catch (Exception e) { System.out.println("XML Pasing Excpetion = " + e); } } }

    Read the article

  • android populating gridivew from a url string

    - by user1685991
    I am building an android application in which i am trying to read data from a url and want to display the data in a gridview. But i have some problem or dont understand to how to display the array list on grdiview. Here is my code for reading data from php url ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //http post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://sml.com.pk/a/smldb.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection"+e.toString()); } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line="0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //paring data double des; double value; try{ jArray = new JSONArray(result); JSONObject json_data=null; for(int i=0;i<jArray.length();i++){ json_data = jArray.getJSONObject(i); LAT=json_data.getDouble("TITLE"); LANG=json_data.getDouble("A"); } } catch(JSONException e1){ Toast.makeText(getBaseContext(), "No Vehicles Found" ,Toast.LENGTH_LONG).show(); } catch (ParseException e1) { e1.printStackTrace(); } Here TITLE and A are my two columns of DB Table and i want to display them on gridview please any one help me to do this according to my current code. Here is my live url for data string http://sml.com.pk/a/smldb.php

    Read the article

  • InputStreamBody in HttpMime 4.0.3 settings for content-length

    - by Ram
    I am trying to send a multi part formdata post through my java code. Can someone tell me how to set Content Length in the following?? There seem to be headers involved when we use InputStreamBody which implements the ContentDescriptor interface. Doing a getContentLength on the InputStreamBody gives me -1 after i add the content. I subclassed it to give contentLength the length of my byte array but am not sure if other headers required by ContentDescriptor will be set for a proper POST. HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(myURL); ContentBody cb = new InputStreamBody(new ByteArrayInputStream(bytearray), myMimeType, filename); //ContentBody cb = new ByteArrayBody(bytearray, myMimeType, filename); MultipartEntity mpentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); mpentity.addPart("key", new StringBody("SOME_KEY")); mpentity.addPart("output", new StringBody("SOME_NAME")); mpentity.addPart("content", cb); httpPost.setEntity(mpentity); HttpResponse response = httpclient.execute(httpPost); HttpEntity resEntity = response.getEntity();

    Read the article

  • Reusing OAuth request token when user refresh page - Twitter4j on GAE

    - by Tahir Akram
    Hi I am using Twitter4J API on GAE/J. I want to use the request token when user came to my page. (called back URL). And press refresh button. I write following code for that. But When user press refresh button. I got Authentication credentials error. Please see the stacktrance. It works fine when user first time used that token. HomeServlet.java code: HttpSession session = request.getSession(); twitter.setOAuthConsumer(FFConstants.CONSUMER_KEY, FFConstants.CONSUMER_SECRET); String token = (String) session.getAttribute("token"); String authorizedToken = (String)session.getAttribute("authorizedToken"); User user = null; if (!token.equals(authorizedToken)){ AccessToken accessToken = twitter.getOAuthAccessToken( token, (String) session .getAttribute("tokenSecret")); twitter.setOAuthAccessToken(accessToken); user = twitter.verifyCredentials(); session.setAttribute("authorizedToken", token); session.setAttribute("user", user); }else{ user = (User)session.getAttribute("user"); } TwitterUser twitterUser = new TwitterUser(); twitterUser.setFollowersCount(user.getFollowersCount()); twitterUser.setFriendsCount(user.getFriendsCount()); twitterUser.setFullName(user.getName()); twitterUser.setScreenName(user.getScreenName()); twitterUser.setLocation(user.getLocation()); Please suggest how I can do that. I have seen on many website. They retain the user with the same token. Even if user press browser refresh buttion again and again. Please help. Exception stacktrace: Reason: twitter4j.TwitterException: 401:Authentication credentials were missing or incorrect. /friends/ids.xml This method requires authentication. at twitter4j.http.HttpClient.httpRequest(HttpClient.java:469) at twitter4j.http.HttpClient.get(HttpClient.java:412) at twitter4j.Twitter.get(Twitter.java:276) at twitter4j.Twitter.get(Twitter.java:228) at twitter4j.Twitter.getFriendsIDs(Twitter.java:1819) at com.tff.servlet.HomeServlet.doGet(HomeServlet.java:86) at javax.servlet.http.HttpServlet.service(HttpServlet.java:693) 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$CachedChain.doFilter(ServletHandler.java:1093) at com.google.apphosting.utils.servlet.ParseBlobUploadFilter.doFilter(ParseBlobUploadFilter.java:97) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084) at com.google.apphosting.runtime.jetty.SaveSessionFilter.doFilter(SaveSessionFilter.java:35) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084) at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43) at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1084) at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:360) 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:712) at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405) at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.handle(AppVersionHandlerMap.java:238) at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:139) at org.mortbay.jetty.Server.handle(Server.java:313) at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:506) at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:830) at com.google.apphosting.runtime.jetty.RpcRequestParser.parseAvailable(RpcRequestParser.java:76) at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:381) at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:135) at com.google.apphosting.runtime.JavaRuntime.handleRequest(JavaRuntime.java:235) at com.google.apphosting.base.RuntimePb$EvaluationRuntime$6.handleBlockingRequest(RuntimePb.java:5235) at com.google.apphosting.base.RuntimePb$EvaluationRuntime$6.handleBlockingRequest(RuntimePb.java:5233) at com.google.net.rpc.impl.BlockingApplicationHandler.handleRequest(BlockingApplicationHandler.java:24) at com.google.net.rpc.impl.RpcUtil.runRpcInApplication(RpcUtil.java:363) at com.google.net.rpc.impl.Server$2.run(Server.java:838) at com.google.tracing.LocalTraceSpanRunnable.run(LocalTraceSpanRunnable.java:56) at com.google.tracing.LocalTraceSpanBuilder.internalContinueSpan(LocalTraceSpanBuilder.java:536) at com.google.net.rpc.impl.Server.startRpc(Server.java:793) at com.google.net.rpc.impl.Server.processRequest(Server.java:368) at com.google.net.rpc.impl.ServerConnection.messageReceived(ServerConnection.java:448) at com.google.net.rpc.impl.RpcConnection.parseMessages(RpcConnection.java:319) at com.google.net.rpc.impl.RpcConnection.dataReceived(RpcConnection.java:290) at com.google.net.async.Connection.handleReadEvent(Connection.java:466) at com.google.net.async.EventDispatcher.processNetworkEvents(EventDispatcher.java:759) at com.google.net.async.EventDispatcher.internalLoop(EventDispatcher.java:205) at com.google.net.async.EventDispatcher.loop(EventDispatcher.java:101) at com.google.net.rpc.RpcService.runUntilServerShutdown(RpcService.java:251) at com.google.apphosting.runtime.JavaRuntime$RpcRunnable.run(JavaRuntime.java:394) at java.lang.Thread.run(Unknown Source)

    Read the article

  • mysql db connection

    - by Dragster
    hi there i have been searching the web for a connection between my android simulator and a mysql db. I've fount that you can't connect directly but via a webserver. The webserver wil handle my request from my android. I fount the following code on www.helloandroid.com But i don't understand. If i run this code on the simulator nothing happens. The screen stays black. Where does Log.i land. In the android screen or in the error log or somewhere else? Can somebody help me with this code? package app.android.ticket; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class fetchData extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //call the method to run the data retreival getServerData(); } public static final String KEY_121 = "http://www.jorisdek.nl/android/getAllPeopleBornAfter.php"; public fetchData() { Log.e("fetchData", "Initialized ServerLink "); } private void getServerData() { InputStream is = null; String result = ""; //the year data to send ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("year","1980")); //http post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(KEY_121); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString()); } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //parse json data try{ JSONArray jArray = new JSONArray(result); for(int i=0;i<jArray.length();i++){ JSONObject json_data = jArray.getJSONObject(i); Log.i("log_tag","id: "+json_data.getInt("id")+ ", name: "+json_data.getString("name")+ ", sex: "+json_data.getInt("sex")+ ", birthyear: "+json_data.getInt("birthyear") ); } }catch(JSONException e){ Log.e("log_tag", "Error parsing data "+e.toString()); } } }

    Read the article

  • Retrieve XML from URL

    - by Pl4za
    I am having some problems retrieving a xml from url with the following code: private static String getAlbumArt(String artistName, String albumName){ try{ XMLParser xml_parser = new XMLParser(); String xml = xml_parser.getXmlFromUrl(getAlbumURL(artistName, albumName)); Document doc = xml_parser.getDomElement(xml); NodeList N = doc.getElementsByTagName("album"); Node node = N.item(0); NodeList N2 = node.getChildNodes(); System.out.println("1------"); for (int i = 0; i < N2.getLength(); i++) { Node detailNode = N2.item(i); if (detailNode.getNodeType() == Node.ELEMENT_NODE) { System.out.println("2------"); if (detailNode.getNodeName().equalsIgnoreCase("image")) { String sizeVal = ((Element) detailNode).getAttribute("size"); String url = detailNode.getTextContent(); if (sizeVal.equalsIgnoreCase("large")) { return url; } } } } } catch (Exception e){ } return null; } The xml function which i call in the above code: public String getXmlFromUrl(String url) { String xml = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); xml = EntityUtils.toString(httpEntity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return xml; } getAlbumURL: public static String getAlbumURL(String artist, String album){ return URL_METHOD + METHOD_GETALBUM + AMPERSAND + API_KEY + AMPERSAND + PARAM_ARTIST + artist + AMPERSAND + PARAM_ALBUM + album; } XMLparser: public class XMLParser { // constructor public XMLParser() { } //Get XML from URL public String getXmlFromUrl(String url) { String xml = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); xml = EntityUtils.toString(httpEntity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return xml; } //Get dom element public Document getDomElement(String xml){ Document doc = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); doc = db.parse(is); } catch (ParserConfigurationException e) { Log.e("Error: ", e.getMessage()); return null; } catch (SAXException e) { Log.e("Error: ", e.getMessage()); return null; } catch (IOException e) { Log.e("Error: ", e.getMessage()); return null; } return doc; } //Get nod element public final String getElementValue(Node elem ) { Node child; if( elem != null){ if (elem.hasChildNodes()){ for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){ if( child.getNodeType() == Node.TEXT_NODE ){ return child.getNodeValue(); } } } } return ""; } //Get element value public String getValue(Element item, String str) { NodeList nlList = item.getElementsByTagName(str).item(0).getChildNodes(); Node nValue = (Node) nlList.item(0); return nValue.getNodeValue(); } } Any ideas ? I seriously don't know what is wrong.. I used this before and it worked.

    Read the article

  • Using AsyncTask, but experiencing unexpected behaviour

    - by capcom
    Please refer to the following code which continuously calls a new AsyncTask. The purpose of the AsyncTask is to make an HTTP request, and update the string result. package room.temperature; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class RoomTemperatureActivity extends Activity { String result = null; StringBuilder sb=null; TextView TemperatureText, DateText; ArrayList<NameValuePair> nameValuePairs; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TemperatureText = (TextView) findViewById(R.id.temperature); DateText = (TextView) findViewById(R.id.date); nameValuePairs = new ArrayList<NameValuePair>(); for (int i = 0; i < 10; i++) { RefreshValuesTask task = new RefreshValuesTask(); task.execute(""); } } // The definition of our task class private class RefreshValuesTask extends AsyncTask<String, Integer, String> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { InputStream is = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://mywebsite.com/roomtemp/tempscript.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch(Exception e) { Log.e("log_tag", "Error in http connection" + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); sb = new StringBuilder(); sb.append(reader.readLine()); is.close(); result=sb.toString(); } catch(Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } return result; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); //System.out.println(result); setValues(result); } } public void setValues(String resultValue) { System.out.println(resultValue); String[] values = resultValue.split("&"); TemperatureText.setText(values[0]); DateText.setText(values[1]); } } The problem I am experiencing relates to the AsyncTask in some way or the function setValues(), but I am not sure how. Essentially, I want each call to the AsyncTask to run, eventually in an infinite while loop, and update the TextView fields as I have attempted in setValues. I have tried since yesterday after asking a question which led to this code, for reference. Oh yes, I did try using the AsyncTask get() method, but that didn't work either as I found out that it is actually a synchronous call, and renders the whole point of AsyncTask useless.

    Read the article

  • JSON error Caused by: java.lang.NullPointerException

    - by user3821853
    im trying to make a register page on android using JSON. everytime i press register button on avd, i get an error "unfortunately database has stopped". i have a error on my logcat that i cannot understand. this my code. please someone help me. this my register.java import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class Register extends Activity implements OnClickListener{ private EditText user, pass; private Button mRegister; // Progress Dialog private ProgressDialog pDialog; // JSON parser class JSONParser jsonParser = new JSONParser(); //php register script //localhost : //testing on your device //put your local ip instead, on windows, run CMD > ipconfig //or in mac's terminal type ifconfig and look for the ip under en0 or en1 // private static final String REGISTER_URL = "http://xxx.xxx.x.x:1234/webservice/register.php"; //testing on Emulator: private static final String REGISTER_URL = "http://10.0.2.2:1234/webservice/register.php"; //testing from a real server: //private static final String REGISTER_URL = "http://www.mybringback.com/webservice/register.php"; //ids private static final String TAG_SUCCESS = "success"; private static final String TAG_MESSAGE = "message"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.register); user = (EditText)findViewById(R.id.username); pass = (EditText)findViewById(R.id.password); mRegister = (Button)findViewById(R.id.register); mRegister.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub new CreateUser().execute(); } class CreateUser extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Register.this); pDialog.setMessage("Creating User..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... args) { // TODO Auto-generated method stub // Check for success tag int success; String username = user.getText().toString(); String password = pass.getText().toString(); try { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); Log.d("request!", "starting"); //Posting user data to script JSONObject json = jsonParser.makeHttpRequest( REGISTER_URL, "POST", params); // full json response Log.d("Registering attempt", json.toString()); // json success element success = json.getInt(TAG_SUCCESS); if (success == 1) { Log.d("User Created!", json.toString()); finish(); return json.getString(TAG_MESSAGE); }else{ Log.d("Registering Failure!", json.getString(TAG_MESSAGE)); return json.getString(TAG_MESSAGE); } } catch (JSONException e) { e.printStackTrace(); } return null; } protected void onPostExecute(String file_url) { // dismiss the dialog once product deleted pDialog.dismiss(); if (file_url != null){ Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show(); } } } } this is JSONparser.java import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(final String url) { // Making HTTP request try { // Construct the client and the HTTP request. DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); // Execute the POST request and store the response locally. HttpResponse httpResponse = httpClient.execute(httpPost); // Extract data from the response. HttpEntity httpEntity = httpResponse.getEntity(); // Open an inputStream with the data content. is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { // Create a BufferedReader to parse through the inputStream. BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); // Declare a string builder to help with the parsing. StringBuilder sb = new StringBuilder(); // Declare a string to store the JSON object data in string form. String line = null; // Build the string until null. while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } // Close the input stream. is.close(); // Convert the string builder data to an actual string. json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // Try to parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // Return the JSON Object. return jObj; } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } and this my error 08-18 23:40:02.381 2000-2018/com.example.blackcustomzier.database E/Buffer Error? Error converting result java.lang.NullPointerException: lock == null 08-18 23:40:02.381 2000-2018/com.example.blackcustomzier.database E/JSON Parser? Error parsing data org.json.JSONException: End of input at character 0 of 08-18 23:40:02.391 2000-2018/com.example.blackcustomzier.database W/dalvikvm? threadid=15: thread exiting with uncaught exception (group=0xb0f37648) 08-18 23:40:02.391 2000-2018/com.example.blackcustomzier.database E/AndroidRuntime? FATAL EXCEPTION: AsyncTask #4 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:299) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) at java.util.concurrent.FutureTask.setException(FutureTask.java:219) at java.util.concurrent.FutureTask.run(FutureTask.java:239) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) at java.lang.Thread.run(Thread.java:841) Caused by: java.lang.NullPointerException at com.example.blackcustomzier.database.Register$CreateUser.doInBackground(Register.java:108) at com.example.blackcustomzier.database.Register$CreateUser.doInBackground(Register.java:74) at android.os.AsyncTask$2.call(AsyncTask.java:287) at java.util.concurrent.FutureTask.run(FutureTask.java:234)             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)             at java.lang.Thread.run(Thread.java:841) 08-18 23:40:02.501 2000-2000/com.example.blackcustomzier.database W/EGL_emulation? eglSurfaceAttrib not implemented 08-18 23:40:02.591 2000-2000/com.example.blackcustomzier.database W/EGL_emulation? eglSurfaceAttrib not implemented 08-18 23:40:02.981 2000-2000/com.example.blackcustomzier.database E/WindowManager? Activity com.example.blackcustomzier.database.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b1294c60 V.E..... R......D 0,0-1026,288} that was originally added here android.view.WindowLeaked: Activity com.example.blackcustomzier.database.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b1294c60 V.E..... R......D 0,0-1026,288} that was originally added here at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) at android.app.Dialog.show(Dialog.java:281) at com.example.blackcustomzier.database.Register$CreateUser.onPreExecute(Register.java:85) at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586) at android.os.AsyncTask.execute(AsyncTask.java:534) at com.example.blackcustomzier.database.Register.onClick(Register.java:70) at android.view.View.performClick(View.java:4240) at android.view.View.onKeyUp(View.java:7928) at android.widget.TextView.onKeyUp(TextView.java:5606) at android.view.KeyEvent.dispatch(KeyEvent.java:2647) at android.view.View.dispatchKeyEvent(View.java:7343) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1393) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1393) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1393) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1393) at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1933) at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1408) at android.app.Activity.dispatchKeyEvent(Activity.java:2384) at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1860) at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:3791) at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3774) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398) at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406) at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398) at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3516) at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:3666) at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:1982) at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1698) at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1689) at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:1959) at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141) at android.os.MessageQueue.nativePollOnce(Native Method) at android.os.MessageQueue.next(MessageQueue.java:132) at android.os.Looper.loop(Looper.java:124) at android.app.ActivityThread.main(ActivityThread.java:5103) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCal please help me to solve this thx

    Read the article

  • ASP.NET Web API and Simple Value Parameters from POSTed data

    - by Rick Strahl
    In testing out various features of Web API I've found a few oddities in the way that the serialization is handled. These are probably not super common but they may throw you for a loop. Here's what I found. Simple Parameters from Xml or JSON Content Web API makes it very easy to create action methods that accept parameters that are automatically parsed from XML or JSON request bodies. For example, you can send a JavaScript JSON object to the server and Web API happily deserializes it for you. This works just fine:public string ReturnAlbumInfo(Album album) { return album.AlbumName + " (" + album.YearReleased.ToString() + ")"; } However, if you have methods that accept simple parameter types like strings, dates, number etc., those methods don't receive their parameters from XML or JSON body by default and you may end up with failures. Take the following two very simple methods:public string ReturnString(string message) { return message; } public HttpResponseMessage ReturnDateTime(DateTime time) { return Request.CreateResponse<DateTime>(HttpStatusCode.OK, time); } The first one accepts a string and if called with a JSON string from the client like this:var client = new HttpClient(); var result = client.PostAsJsonAsync<string>(http://rasxps/AspNetWebApi/albums/rpc/ReturnString, "Hello World").Result; which results in a trace like this: POST http://rasxps/AspNetWebApi/albums/rpc/ReturnString HTTP/1.1Content-Type: application/json; charset=utf-8Host: rasxpsContent-Length: 13Expect: 100-continueConnection: Keep-Alive "Hello World" produces… wait for it: null. Sending a date in the same fashion:var client = new HttpClient(); var result = client.PostAsJsonAsync<DateTime>(http://rasxps/AspNetWebApi/albums/rpc/ReturnDateTime, new DateTime(2012, 1, 1)).Result; results in this trace: POST http://rasxps/AspNetWebApi/albums/rpc/ReturnDateTime HTTP/1.1Content-Type: application/json; charset=utf-8Host: rasxpsContent-Length: 30Expect: 100-continueConnection: Keep-Alive "\/Date(1325412000000-1000)\/" (yes still the ugly MS AJAX date, yuk! This will supposedly change by RTM with Json.net used for client serialization) produces an error response: The parameters dictionary contains a null entry for parameter 'time' of non-nullable type 'System.DateTime' for method 'System.Net.Http.HttpResponseMessage ReturnDateTime(System.DateTime)' in 'AspNetWebApi.Controllers.AlbumApiController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Basically any simple parameters are not parsed properly resulting in null being sent to the method. For the string the call doesn't fail, but for the non-nullable date it produces an error because the method can't handle a null value. This behavior is a bit unexpected to say the least, but there's a simple solution to make this work using an explicit [FromBody] attribute:public string ReturnString([FromBody] string message) andpublic HttpResponseMessage ReturnDateTime([FromBody] DateTime time) which explicitly instructs Web API to read the value from the body. UrlEncoded Form Variable Parsing Another similar issue I ran into is with POST Form Variable binding. Web API can retrieve parameters from the QueryString and Route Values but it doesn't explicitly map parameters from POST values either. Taking our same ReturnString function from earlier and posting a message POST variable like this:var formVars = new Dictionary<string,string>(); formVars.Add("message", "Some Value"); var content = new FormUrlEncodedContent(formVars); var client = new HttpClient(); var result = client.PostAsync(http://rasxps/AspNetWebApi/albums/rpc/ReturnString, content).Result; which produces this trace: POST http://rasxps/AspNetWebApi/albums/rpc/ReturnString HTTP/1.1Content-Type: application/x-www-form-urlencodedHost: rasxpsContent-Length: 18Expect: 100-continue message=Some+Value When calling ReturnString:public string ReturnString(string message) { return message; } unfortunately it does not map the message value to the message parameter. This sort of mapping unfortunately is not available in Web API. Web API does support binding to form variables but only as part of model binding, which binds object properties to the POST variables. Sending the same message as in the previous example you can use the following code to pick up POST variable data:public string ReturnMessageModel(MessageModel model) { return model.Message; } public class MessageModel { public string Message { get; set; }} Note that the model is bound and the message form variable is mapped to the Message property as would other variables to properties if there were more. This works but it's not very dynamic. There's no real easy way to retrieve form variables (or query string values for that matter) in Web API's Request object as far as I can discern. Well only if you consider this easy:public string ReturnString() { var formData = Request.Content.ReadAsAsync<FormDataCollection>().Result; return formData.Get("message"); } Oddly FormDataCollection does not allow for indexers to work so you have to use the .Get() method which is rather odd. If you're running under IIS/Cassini you can always resort to the old and trusty HttpContext access for request data:public string ReturnString() { return HttpContext.Current.Request.Form["message"]; } which works fine and is easier. It's kind of a bummer that HttpRequestMessage doesn't expose some sort of raw Request object that has access to dynamic data - given that it's meant to serve as a generic REST/HTTP API that seems like a crucial missing piece. I don't see any way to read query string values either. To me personally HttpContext works, since I don't see myself using self-hosted code much.© Rick Strahl, West Wind Technologies, 2005-2012Posted in Web Api   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • ASP.NET WebAPI Security 4: Examples for various Authentication Scenarios

    - by Your DisplayName here!
    The Thinktecture.IdentityModel.Http repository includes a number of samples for the various authentication scenarios. All the clients follow a basic pattern: Acquire client credential (a single token, multiple tokens, username/password). Call Service. The service simply enumerates the claims it finds on the request and returns them to the client. I won’t show that part of the code, but rather focus on the step 1 and 2. Basic Authentication This is the most basic (pun inteneded) scenario. My library contains a class that can create the Basic Authentication header value. Simply set username and password and you are good to go. var client = new HttpClient { BaseAddress = _baseAddress }; client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue("alice", "alice"); var response = client.GetAsync("identity").Result; response.EnsureSuccessStatusCode();   SAML Authentication To integrate a Web API with an existing enterprise identity provider like ADFS, you can use SAML tokens. This is certainly not the most efficient way of calling a “lightweight service” ;) But very useful if that’s what it takes to get the job done. private static string GetIdentityToken() {     var factory = new WSTrustChannelFactory(         new WindowsWSTrustBinding(SecurityMode.Transport),         _idpEndpoint);     factory.TrustVersion = TrustVersion.WSTrust13;     var rst = new RequestSecurityToken     {         RequestType = RequestTypes.Issue,         KeyType = KeyTypes.Bearer,         AppliesTo = new EndpointAddress(Constants.Realm)     };     var token = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;     return token.TokenXml.OuterXml; } private static Identity CallService(string saml) {     var client = new HttpClient { BaseAddress = _baseAddress };     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SAML", saml);     var response = client.GetAsync("identity").Result;     response.EnsureSuccessStatusCode();     return response.Content.ReadAsAsync<Identity>().Result; }   SAML to SWT conversion using the Azure Access Control Service Another possible options for integrating SAML based identity providers is to use an intermediary service that allows converting the SAML token to the more compact SWT (Simple Web Token) format. This way you only need to roundtrip the SAML once and can use the SWT afterwards. The code for the conversion uses the ACS OAuth2 endpoint. The OAuth2Client class is part of my library. private static string GetServiceTokenOAuth2(string samlToken) {     var client = new OAuth2Client(_acsOAuth2Endpoint);     return client.RequestAccessTokenAssertion(         samlToken,         SecurityTokenTypes.Saml2TokenProfile11,         Constants.Realm).AccessToken; }   SWT Authentication When you have an identity provider that directly supports a (simple) web token, you can acquire the token directly without the conversion step. Thinktecture.IdentityServer e.g. supports the OAuth2 resource owner credential profile to issue SWT tokens. private static string GetIdentityToken() {     var client = new OAuth2Client(_oauth2Address);     var response = client.RequestAccessTokenUserName("bob", "abc!123", Constants.Realm);     return response.AccessToken; } private static Identity CallService(string swt) {     var client = new HttpClient { BaseAddress = _baseAddress };     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", swt);     var response = client.GetAsync("identity").Result;     response.EnsureSuccessStatusCode();     return response.Content.ReadAsAsync<Identity>().Result; }   So you can see that it’s pretty straightforward to implement various authentication scenarios using WebAPI and my authentication library. Stay tuned for more client samples!

    Read the article

  • Connect Orbeon Xform to External Exist DB

    - by user302254
    I am attempting to connect a new Orbeon XForm to an existing exist db. My code should submit an xml doc to be stored in that database. <xf:submission id="save-to-file" method="get" action="http://server:8081/exist/rest//test/test/inventory_sample.xml" replace="instance" instance="data-instance" includenamespaceprefixes="ai"/> When attempting to submit my xml file, my log reveals an authentication error: Apr 6, 2010 2:06:08 PM org.apache.commons.httpclient.auth.AuthChallengeProcessor selectAuthScheme INFO: basic authentication scheme selected Apr 6, 2010 2:06:08 PM org.apache.commons.httpclient.HttpMethodDirector processW WWAuthChallenge INFO: No credentials available for BASIC 'exist'@kruddler.mitre.org:8081 How do I authenticate this connection ?

    Read the article

  • Getting the username in Twitter using OAuth 0.1.1 Grails plugin

    - by firnnauriel
    anyone had tried using http://www.grails.org/plugin/oauth? i'm trying it in twitter.com and i'm having an issue on getting the username or accessing this API: http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-account%C2%A0verify_credentials here's the code in my callback URL: def twitterCallback = { def response = oauthService.accessResource('http://api.twitter.com/1/account/verify_credentials.json','twitter', session.oauthToken) log.debug "response: ${response}" } i keep getting this error: 2010-04-22 14:32:56,842 [http-8081-1] WARN httpclient.HttpMethodBase - Cookie rejected: "$Version=0; _twitter_sess=BAh7CDoPY3JlYXRlZF9hdGwrCMQcOCQoAToHaWQiJThiYWY4MGI1YTY1M2U0%250AYTRhNjAzYTA2NTBmNjkzZTYwIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVy%250AOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--31d191141bf32e0489967492692f1e77fc9e1845; $Path=/; $Domain=.twitter.com". Illegal domain attribute ".twitter.com". Domain of origin: "twitter.com" 2010-04-22 14:32:56,854 [http-8081-1] INFO auth.AuthChallengeProcessor - basic authentication scheme selected 2010-04-22 14:32:56,856 [http-8081-1] INFO httpclient.HttpMethodDirector - No credentials available for BASIC 'Twitter API'@twitter.com:80 2010-04-22 14:32:56,865 [http-8081-1] ERROR errors.GrailsExceptionResolver - null it seems that it uses BASIC authentication instead of OAuth. any ideas? or is there an issue in the OAuth Grails plugin? thanks.

    Read the article

  • Best practices for developing bigger applications on Android

    - by Janusz
    I've already written some small Android Applications, most of them in one Activity and nearly no data that should be persistent on the device. Now I'm writing an application that needs more Activities and I'm a bit puzzled about how to organize all this. My app will download some data parse it show it to the user and then show other activities depending on the data and the user interaction. Some of that data could be cached, some of it has to be downloaded every time. Some of that data should not be downloaded freshly at the moment the orientation changes, but it should on the moment the activity is created... Another thing I'm confused about are things like a httpClient. I now for example create a new httpclient for every activity, the same thing for locationlisteners. Are there books, a blogs or documentations with patterns, examples and advice on organizing larger apps build on android? Everything I found until now are get startet tutorials leaving me alone after 60 lines of code...

    Read the article

  • Connect MySQL database from Android

    - by Mistry Hardik
    hello people! well this is the code snippet i use to access the getUser.php to retrive user details from a MySQL database in my application: String result = ""; //the year data to send ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("uid","demo")); //http post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://192.xxx.xx.xxx/getUser.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString()); } //convert response to string try{ InputStream is = null; BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //parse json data try{ JSONArray jArray = new JSONArray(result); for(int i=0;i<jArray.length();i++){ JSONObject json_data = jArray.getJSONObject(i); Log.i("log_tag","id: "+json_data.getInt("id")+ ", name: "+json_data.getString("fname")+ ", sex: "+json_data.getInt("sex")+ ", birthyear: "+json_data.getInt("dob") ); } } catch(JSONException e){ Log.e("log_tag", "Error parsing data "+e.toString()); } } This snippet is taken from http://helloandroid.com Everything is configured fine: the MySQL Db, IIS with FASTCGi, PHP tools and drivers. even the script below when called from browser with url: http://192.xxx.xx.x.xxx/getUser.php?uid=demo works fine, But returns error in android with java.lang.NullPointerException and org.json.JSONEXCEPTION: End of input at character 0 <?php mysql_connect("myhost","username","pwd"); mysql_select_db("mydb"); $q=mysql_query("SELECT * FROM userinfo WHERE uid ='".$_REQUEST['uid']."'"); while($e=mysql_fetch_assoc($q)) $output[]=$e; print(json_encode($output)); mysql_close(); ?> Can anybody help in this section? Regards, Mistry Hardik

    Read the article

  • Posting comments to a wordpress-blog in Android

    - by Samuh
    I am working on a module that allows users to post comments on a blog published on Wordpress. I looked at the HTML source for Post-Comment-Form displayed at the bottom of a blog entry (Leave a Reply section). Using that as a reference, I translated it to Java using DefaultHTTPClient and BasicNameValuePairs and my code looks like: DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://xycabz.wordpress.com/wp-comments-post.php"); httppost.setHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("author","abc")); nvps.add(new BasicNameValuePair("email","[email protected]")); nvps.add(new BasicNameValuePair("url","")); nvps.add(new BasicNameValuePair("comment","entiendamonos?")); nvps.add(new BasicNameValuePair("comment_post_ID","123")); //this was a hidden field and always set to 0 nvps.add(new BasicNameValuePair("comment_parent","0")); try { httppost.setEntity(new UrlEncodedFormEntity(nvps)); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } BasicResponseHandler handler = new BasicResponseHandler(); try { Log.e("OUTPUT",httpclient.execute(httppost,handler)); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } The above code works fine when I try it out on my blog. But when I try this on the actual blog, I get HTTP 302 Found (Redirect to temporary location) exceptions in the logs. The comments never make it to the blog page. Usually, when you post a comment(on the web page) you are taken back to the blog page that enlists all the comments. The URL I am getting in the redirects is the same. Questions: 1. Could this be a post-a-comment settings problem(perhaps something the original blog owner might have set)? 2. How should my HTTPClient handle 302 status code? Eventually, I just have to notify the user of success and failure and not actually take him to the comments page.

    Read the article

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