Search Results

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

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

  • ListView Parsing Persian xml

    - by Namikaze Minato
    I used a tutorial about listview parsing xm from internet and using LasyAdapter shows the items in listview. When I add persian characters in xml (into one of childnodes) the result is some boxes in listview (after showing the text in listview). The format of xml is UTF-8, too. I used typeface too (but didn't work). Besides when I type Pwesian into the application it shows alright but it can't show Persiann content parsed from xml. Thanks in advance. I updated the post with original XMLparser (which was the problem). public String getXmlFromUrl(String url) { String xml = null; try { // defaultHttpClient 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 return xml; } 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; }

    Read the article

  • How to make a request from an android app that can enter a Spring Security secured webservice method

    - by johnrock
    I have a Spring Security (form based authentication) web app running CXF JAX-RS webservices and I am trying to connect to this webservice from an Android app that can be authenticated on a per user basis. Currently, when I add an @Secured annotation to my webservice method all requests to this method are denied. I have tried to pass in credentials of a valid user/password (that currently exists in the Spring Security based web app and can log in to the web app successfully) from the android call but the request still fails to enter this method when the @Secured annotation is present. The SecurityContext parameter returns null when calling getUserPrincipal(). How can I make a request from an android app that can enter a Spring Security secured webservice method? Here is the code I am working with at the moment: Android call: httpclient.getCredentialsProvider().setCredentials( //new AuthScope("192.168.1.101", 80), new AuthScope(null, -1), new UsernamePasswordCredentials("joeuser", "mypassword")); String userAgent = "Android/" + getVersion(); HttpGet httpget = new HttpGet(MY_URI); httpget.setHeader("User-Agent", userAgent); httpget.setHeader("Content-Type", "application/xml"); HttpResponse response; try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); ... parse xml Webservice Method: @GET @Path("/payload") @Produces("application/XML") @Secured({"ROLE_USER","ROLE_ADMIN","ROLE_GUEST"}) public Response makePayload(@Context Request request, @Context SecurityContext securityContext){ Payload payload = new Payload(); payload.setUsersOnline(new Long(200)); if (payload == null) { return Response.noContent().build(); } else{ return Response.ok().entity(payload).build(); } }

    Read the article

  • Persistant Http client connections in java

    - by Akusete
    I am trying to write a simple Http client application in Java and am a bit confused by the seemingly different ways to establish Http client connections, and efficiently re-use the objects. Current I am using the following steps (I have left out exception handling for simplicity) Iterator<URI> uriIterator = someURIs(); HttpClient client = new DefaultHttpClient(); while (uriIterator.hasNext()) { URI uri = uriIterator.next(); HttpGet request = new HttpGet(uri); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); InputStream s = entity.getContent(); processStream (); s.close(); } In regard to the code above, my questions is: Assuming all URI's are pointing to the same host (but different resources on that host). What is the recommended way to use a single http connection for all requests? And how do you close the connection after the last request? --edit: Also what is the difference between using uri.openConnection(), versus HttpClient? Which is preferable, and what other methods exist?

    Read the article

  • Third party multipart request in playframework

    - by Brian
    I'm making an application to post photos to yfrog and twitpic and I am having a little trouble figuring out how to set the parameters. Here is my code: public static Result index() { HttpClient httpclient = new DefaultHttpClient(); WSRequestHolder holder = WS.url("http://api.twitpic.com/2/upload.json"); holder.setHeader("Authorization", ""); return async(holder.post("").map(new Function<WS.Response, Result>() { public Result apply(WS.Response response) { return ok(response.getBody()); } })); } Now, I don't expect this to actually get an ok response from the server, as I am just testing the responses that I get back from the server, and that is one that says I need to provide the api key. I figured as much, but I'm not sure of the syntax for providing that parameter, as I need to also give the name of the file and the file. I tried setting holder.post("key=somekey"), with the hope that I would get a different error message (like the key you provided is invalid) but I just get the same error. I'm assuming that I probably need to send it in the for of a multipart request, but I am not very experienced with this kind of request and can't find any play documentation on how to create a multipart request, other than in an html form. Any suggestions and help will be much appreciated. And fyi, I do know that there are yfrog and twitpic java classes to handle this kind of stuff, but I want to do it myself, more so for learning how to do this kind of stuff. Thanks in advance!

    Read the article

  • Post complex types to WebApi Client

    - by BumbleBee
    I am new to WebAPI. I have a MVC project and webApi project both reside under the **same solution**. Also, BLL Class library and DAL class library reside under the same solution. Earlier, my MVC project will talk to the BLL now I am trying to create a WebAPi project which stands in between MVC and BLL. Here is what I have come up with so far : I'm using the HTTPClient to post to a WebApi project. My post method on my controller accepts a single parameter (a model). StatsCriteria criteria = new StatsCriteria(); ...... var client = new HttpClient(); var response = client.PostAsJsonAsync("http://localhost:52765/api/reports", criteria).Result; ....... Here's the signature for my controller in Webapi [HttpPost] public CMAReportVM Reports([FromBody] StatsCriteria criteria) { var cmaReport = Service3.GetCMAReport(criteria.Mlsnums); //Create Map to enable mapping business object to View Model Mapper.CreateMap<CMAReport, CMAReportVM>(); // Maps model to VM model class var cmaVM = Mapper.Map<CMAReport, CMAReportVM>(cmaReport); reutn cmaVM; } // and here's my routing: config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } I am getting the following 405 : Method not allowed. As the WebAPI and MVC project both reside under same sloution I am not sure where/how to host my webapi.

    Read the article

  • java runtime 6 with socks v5 proxy - Possible?

    - by rwired
    I have written an application that (amongst other things) runs a local service in windows that acts as a SOCKS v5 proxy for Firefox. I'm in the debugging phase right now and have found certain websites that don't work correctly. For example the Java Applet for Picture Uploading on Facebook.com fails because is is unable to lookup domains. My app overrides a hidden FF config setting network.proxy.socks__remote__dns setting it to true. The whole purpose of the app is to allow access to websites when behind a firewall (e.g. if the user is in China), so this setting is essential to ensure domains are resolved remotely also (and not just HTTP requests). In the JRE6 settings (documented here) there isn't an equivalent setting, and since remote DNS resolution is a feature of SOCKS v5 and not v4 as the documentation seems to imply I'm worried that it's just not possible. How can I programmatically make sure the JRE uses a SOCKS v5 proxy for all requests (including DNS)? UPDATE: Steps to reproduce this problem: Make sure you are behind a firewall that blocks (or redirects) internet access including DNS Install PuTTY and add a dynamic SSH tunnel on some port number of your choice (e.g. 9870). Then login to a remote server that has full access to the internet Launch Firefox and you will not be able to browse the web In FF network settings set the SOCKS v5 proxy to localhost:9870 In FF go to about:config, change network.proxy.socks__remote__dns to true You will now be able to browse the web. Go to facebook.com, login, go to your profile and attempt to use the picture uploader java applet to add some pictures It will fail with a series of class not found errors looking similar to: load: class com.facebook.facebookphotouploader5.FacebookPhotoUploader5.class not found. I believe this is failing because the JRE is unable to resolve the domain that the class resides on. I'm basing this belief on the fact that the documentation (http://java.sun.com/javase/6/docs/technotes/guides/deployment/deployment-guide/properties.html) talks only about SOCKS v4 (which as far as I know does not support remote DNS). My deployment.properties file is located in %APPDATA%\Sun\Java\Deployment. I can confirm that modifications I make in the Java Control Panel get written into that file. If instead of "Use browser setting" the network settings for Java I override and attempt to use the SOCKS proxy settings manually, I still have the issue. There does not seem to be an easy way to force the JRE to do DNS remotely through the Proxy. UPDATE 2: Without the SOCKS proxy, from my local client www.facebook.com resolves to 203.161.230.171 upload.facebook.com resolves to 64.33.88.161 Neither host is reachable (because of the firewall) If I login to the remote server, I get: www.facebook.com 69.63.187.17 upload.facebook.com 69.63.178.32 Both these IPs change after a few minutes, as it seems Facebook uses round-robin DNS and other load-balancing. With the Proxy settings set in Firefox, I can navigate to www.facebook.com without any difficulty (since DNS is being resolved remotely on the Proxy). Whey I go to the page with the Java applet it fails with the stacktrace messages I've already reported. However if I edit Windows\System32\drivers\etc\hosts, adding the correct IP for upload.facebook.com I can get the applet to load and work correctly (restart of FF is sometimes necessary). This evidence seems to support my theory that the Java Runtime is not resolving DNS on the Proxy, but instead just routing traffic though it. My application is for mass-deployment, and needs to work with java applets on other sites (not just facebook). I really need a work-around for this problem. UPDATE 3 Stacktrace dump a requested by ZZ Coder: load: class com.facebook.facebookphotouploader5.FacebookPhotoUploader5.class not found. java.lang.ClassNotFoundException: com.facebook.facebookphotouploader5.FacebookPhotoUploader5.class at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source) at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source) at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source) at java.lang.Thread.run(Unknown Source) 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 java.net.HttpURLConnection.getResponseCode(Unknown Source) at sun.plugin2.applet.Applet2ClassLoader.getBytes(Unknown Source) at sun.plugin2.applet.Applet2ClassLoader.access$000(Unknown Source) at sun.plugin2.applet.Applet2ClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) ... 7 more Exception: java.lang.ClassNotFoundException: com.facebook.facebookphotouploader5.FacebookPhotoUploader5.class Dumping class loader cache... Live entry: key=http://upload.facebook.com/controls/2008.10.10_v5.5.8/,FacebookPhotoUploader5.jar,FacebookPhotoUploader5.jar, refCount=1, threadGroup=sun.plugin2.applet.Applet2ThreadGroup[name=http://upload.facebook.com/controls/2008.10.10_v5.5.8/-threadGroup,maxpri=4] Done.

    Read the article

  • HttpPost works in Java project, not in Android

    - by dave.c
    I've written some code for my Android device to login to a web site over https and parse some data out of the resulting pages. An HttpGet happens first to get some info needed for login, then an HttpPost to do the actual login process. The code below works great in a Java project within Eclipse which has the following Jar files on the build path: httpcore-4.1-beta2.jar, httpclient-4.1-alpha2.jar, httpmime-4.1-alpha2.jar, commons-logging-1.1.1.jar. public static MyBean gatherData(String username, String password) { MyBean myBean = new MyBean(); try { HttpResponse response = doHttpGet(URL_PAGE_LOGIN, null, null); System.out.println("Got login page"); String content = EntityUtils.toString(response.getEntity()); String token = ContentParser.getToken(content); String cookie = getCookie(response); System.out.println("Performing login"); System.out.println("token = "+token +" || cookie = "+cookie); response = doLoginPost(username,password,cookie, token); int respCode = response.getStatusLine().getStatusCode(); if (respCode != 302) { System.out.println("ERROR: not a 302 redirect!: code is \""+ respCode+"\""); if (respCode == 200) { System.out.println(getHeaders(response)); System.out.println(EntityUtils.toString(response.getEntity()).substring(0, 500)); } } else { System.out.println("Logged in OK, loading account home"); // redirect handler and rest of parse removed } }catch (Exception e) { System.out.println("ERROR in gatherdata: "+e.toString()); e.printStackTrace(); } return myBean; } private static HttpResponse doHttpGet(String url, String cookie, String referrer) { try { HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); HttpGet httpGet = new HttpGet(url); httpGet.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); httpGet.setHeader(HEADER_USER_AGENT,HEADER_USER_AGENT_VALUE); if (referrer != null && !referrer.equals("")) httpGet.setHeader(HEADER_REFERER,referrer); if (cookie != null && !cookie.equals("")) httpGet.setHeader(HEADER_COOKIE,cookie); return client.execute(httpGet); } catch (Exception e) { e.printStackTrace(); throw new ConnectException("Failed to read content from response"); } } private static HttpResponse doLoginPost(String username, String password, String cookie, String token) throws ClientProtocolException, IOException { try { HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); HttpPost post = new HttpPost(URL_LOGIN_SUBMIT); post.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); post.setHeader(HEADER_USER_AGENT,HEADER_USER_AGENT_VALUE); post.setHeader(HEADER_REFERER, URL_PAGE_LOGIN); post.setHeader(HEADER_COOKIE, cookie); post.setHeader("Content-Type","application/x-www-form-urlencoded"); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); formParams.add(new BasicNameValuePair("org.apache.struts.taglib.html.TOKEN", token)); formParams.add(new BasicNameValuePair("showLogin", "true")); formParams.add(new BasicNameValuePair("upgrade", "")); formParams.add(new BasicNameValuePair("username", username)); formParams.add(new BasicNameValuePair("password", password)); formParams.add(new BasicNameValuePair("submit", "Secure+Log+in")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams,HTTP.UTF_8); post.setEntity(entity); return client.execute(post); } catch (Exception e) { e.printStackTrace(); throw new ConnectException("ERROR in doLoginPost(): "+e.getMessage()); } } The server (which is not under my control) returns a 302 redirect when the login was successful, and 200 if it fails and re-loads the login page. When run with the above Jar files I get the 302 redirect, however if I run the exact same code from an Android project with the 1.6 Android Jar file on the build path I get the 200 response from the server. I get the same 200 response when running the code on my 2.2 device. My android application has internet permissions, and the HttpGet works fine. I'm assuming that the problem lies in the fact that HttpPost (or some other class) is different in some significant way between the Android Jar version and the newer Apache versions. I've tried adding the Apache libraries to the build path of the Android project, but due to the duplicate classes I get messages like: INFO/dalvikvm(390): DexOpt: not resolving ambiguous class 'Lorg/apache/http/impl/client/DefaultHttpClient;' in the log. I've also tried using a MultipartEntity instead of the UrlEncodedFormEntity but I get the same 200 result. So, I have a few questions: - Can I force the code running under android to use the newer Apache libraries in preference to the Android versions? - If not, does anyone have any ideas how can I alter my code so that it works with the Android Jar? - Are there any other, totally different approaches to doing an HttpPost in Android? - Any other ideas? I've read a lot of posts and code but I'm not getting anywhere. I've been stuck on this for a couple of days and I'm at a loss how to get the thing to work, so I'll try anything at this point. Thanks in advance.

    Read the article

  • problem in displaying list using array adapters

    - by Rahul Varma
    Hi, I am trying to display the list of songs using array adapters. But the problem is i couldnt display the list and only empty screen with preset background is showing up. Here's the code...All the thee are seperate classes... Plz help me... public class SongsAdapter extends ArrayAdapter<SongsList>{ private Context context; TextView tvTitle; TextView tvMovie; TextView tvSinger; String s; public SongsAdapter(Context context, int resource, int textViewResourceId, String title) { super(context, resource, textViewResourceId); this.context=context; } public View getView(int position, View convertView, ViewGroup parent) { final int i=position; List<SongsList> listSongs = new ArrayList<SongsList>(); String title = listSongs.get(i).gettitleName().toString(); String album = listSongs.get(i).getmovieName().toString(); String artist = listSongs.get(i).getsingerName().toString(); String imgal = listSongs.get(i).gettitleName().toString(); LayoutInflater inflater = ((Activity) context).getLayoutInflater(); View v = inflater.inflate(R.layout.row, null); tvTitle=(TextView)v.findViewById(R.id.text2); tvMovie=(TextView)v.findViewById(R.id.text3); tvSinger=(TextView)v.findViewById(R.id.text1); tvTitle.setText(title); tvMovie.setText(album); tvSinger.setText(artist); final ImageView im=(ImageView)v.findViewById(R.id.image); s="http://www.gorinka.com/"+imgal; String imgPath=s; AsyncImageLoaderv asyncImageLoaderv=new AsyncImageLoaderv(); Bitmap cachedImage = asyncImageLoaderv.loadDrawable(imgPath, new AsyncImageLoaderv.ImageCallback() { public void imageLoaded(Bitmap imageDrawable, String imageUrl) { im.setImageBitmap(imageDrawable); } }); im.setImageBitmap(cachedImage); return v; } public class imageloader implements Runnable{ private String ss; private ImageView im; public imageloader(String s, ImageView im) { this.ss=s; this.im=im; Thread thread = new Thread(this); thread.start(); } public void run(){ try { HttpGet httpRequest = null; httpRequest = new HttpGet(ss); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = (HttpResponse) httpclient.execute(httpRequest); HttpEntity entity = response.getEntity(); BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); InputStream is = bufHttpEntity.getContent(); Bitmap bm = BitmapFactory.decodeStream(is); Log.d("img","img"); is.close(); im.setImageBitmap(bm); } catch (Exception t) { Log.e("bitmap url", "Exception in updateStatus()", t); } } } } public class SongsList { private String titleName; private String movieName; private String singerName; private String imagePath; private String mediaPath; // Constructor for the SongsList class public SongsList(String titleName, String movieName, String singerName,String imagePath,String mediaPath ) { super(); this.titleName = titleName; this.movieName = movieName; this.singerName = singerName; this.imagePath = imagePath; this.mediaPath = mediaPath; } public String gettitleName() { return titleName; } public void settitleName(String titleName) { this.titleName = titleName; } public String getmovieName() { return movieName; } public void setmovieName(String movieName) { this.movieName = movieName; } public String getsingerName() { return singerName; } public void setsingerName(String singerName) { this.singerName = singerName; } public String getimagePath() { return imagePath; } public void setimagePath(String imagePath) { this.imagePath = imagePath; } public String getmediaPath() { return mediaPath; } public void setmediaPath(String mediaPath) { this.mediaPath = mediaPath; } } public class MusicListActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.openadiuofile); ListView list = (ListView)findViewById(R.id.list1); SongsAdapter adapter = new SongsAdapter(this,R.layout.row, R.id.text2, null); list.setAdapter(adapter); } }

    Read the article

  • Facebook implementation in android

    - by Sanat Pandey
    I am implementing Facebook in my app through FbRocket jar, but it gives some error as ClassNotFound, but I don't know why bcoz i have alredy added that jar in libraries........ Please help me out. 05-09 19:04:28.933: ERROR/AndroidRuntime(759): FATAL EXCEPTION: main 05-09 19:04:28.933: ERROR/AndroidRuntime(759): java.lang.NoClassDefFoundError: net.xeomax.FBRocket.FBRocket 05-09 19:04:28.933: ERROR/AndroidRuntime(759): at org.shopzilla.android.moretab.SettingActivity.shareFacebook(SettingActivity.java:73) 05-09 19:04:28.933: ERROR/AndroidRuntime(759): at org.shopzilla.android.moretab.SettingActivity$2.onClick(SettingActivity.java:63) 05-09 19:04:28.933: ERROR/AndroidRuntime(759): at android.view.View.performClick(View.java:2485) 05-09 19:04:28.933: ERROR/AndroidRuntime(759): at android.view.View$PerformClick.run(View.java:9080) 05-09 19:04:28.933: ERROR/AndroidRuntime(759): at android.os.Handler.handleCallback(Handler.java:587) 05-09 19:04:28.933: ERROR/AndroidRuntime(759): at android.os.Handler.dispatchMessage(Handler.java:92) 05-09 19:04:28.933: ERROR/AndroidRuntime(759): at android.os.Looper.loop(Looper.java:123) 05-09 19:04:28.933: ERROR/AndroidRuntime(759): at android.app.ActivityThread.main(ActivityThread.java:3683) 05-09 19:04:28.933: ERROR/AndroidRuntime(759): at java.lang.reflect.Method.invokeNative(Native Method) 05-09 19:04:28.933: ERROR/AndroidRuntime(759): at java.lang.reflect.Method.invoke(Method.java:507) 05-09 19:04:28.933: ERROR/AndroidRuntime(759): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 05-09 19:04:28.933: ERROR/AndroidRuntime(759): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 05-09 19:04:28.933: ERROR/AndroidRuntime(759): at dalvik.system.NativeStart.main(Native Method) Code: package org.shopzilla.android.moretab; import java.util.List; import net.xeomax.FBRocket.FBRocket; import net.xeomax.FBRocket.Facebook; import net.xeomax.FBRocket.ServerErrorException; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.shopzilla.android.common.R; import org.shopzilla.android.facebook.FacebookActivity; import org.shopzilla.android.facebook.FacebookWebOAuthActivity; import org.shopzilla.android.twitter.TwitterActivity; import org.shopzilla.android.twitter.TwitterWebOAuthActivity; import twitter4j.http.RequestToken; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class SettingActivity extends Activity{ String bytesSent; HttpClient httpclient; int count1; // List with parameters and their values List<NameValuePair> nameValuePairs; TextView mText; Button btn_facebook; Button btn_twitter; FBRocket fbRocket; RequestToken rToken; String oauthVerifier; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.more_setting); Button btn_twitter = (Button)findViewById(R.id.btn_more_setting_twitter); Button btn_facebook = (Button)findViewById(R.id.btn_More_setting_facebook); btn_twitter.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent = new Intent(SettingActivity.this,TwitterActivity.class); startActivity(intent); //displayTwitterAuthorization(); } }); btn_facebook.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub /*Intent intent = new Intent(SettingActivity.this,FacebookActivity.class); startActivity(intent);*/ shareFacebook(); //displayFacebookAuthorization(); //shareFacebook(); } }); } public void shareFacebook() { fbRocket = new FBRocket(SettingActivity.this, "ShopZilla", "172619129456913"); if (fbRocket.existsSavedFacebook()) { fbRocket.loadFacebook(); } else { fbRocket.login(R.layout.facebook); } } public void onLoginFail() { fbRocket.displayToast("Login failed!"); fbRocket.login(R.layout.facebook); } public void onLoginSuccess(Facebook facebook) { // TODO Auto-generated method stub fbRocket.displayToast("Login success!"); try { facebook.setStatus("This is your status"); fbRocket.displayDialog("Status Posted Successfully!! " + facebook.getStatus()); } catch (ServerErrorException e) { if (e.notLoggedIn()) { fbRocket.login(R.layout.facebook); } else { System.out.println(e); } } } }

    Read the article

  • Passing data between android ListActivities in Java

    - by Will Janes
    I am new to Android! I am having a problem getting this code to work... Basically I Go from one list activity to another and pass the text from a list item through the intent of the activity to the new list view, then retrieve that text in the new list activity and then preform a http request based on value of that list item. Log Cat 04-05 17:47:32.370: E/AndroidRuntime(30135): FATAL EXCEPTION: main 04-05 17:47:32.370: E/AndroidRuntime(30135): java.lang.ClassCastException:android.widget.LinearLayout 04-05 17:47:32.370: E/AndroidRuntime(30135): at com.thickcrustdesigns.ufood.CatogPage$1.onItemClick(CatogPage.java:66) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.widget.AdapterView.performItemClick(AdapterView.java:284) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.widget.ListView.performItemClick(ListView.java:3731) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1959) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.os.Handler.handleCallback(Handler.java:587) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.os.Handler.dispatchMessage(Handler.java:92) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.os.Looper.loop(Looper.java:130) 04-05 17:47:32.370: E/AndroidRuntime(30135): at android.app.ActivityThread.main(ActivityThread.java:3691) 04-05 17:47:32.370: E/AndroidRuntime(30135): at java.lang.reflect.Method.invokeNative(Native Method) 04-05 17:47:32.370: E/AndroidRuntime(30135): at java.lang.reflect.Method.invoke(Method.java:507) 04-05 17:47:32.370: E/AndroidRuntime(30135): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907) 04-05 17:47:32.370: E/AndroidRuntime(30135): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) 04-05 17:47:32.370: E/AndroidRuntime(30135): at dalvik.system.NativeStart.main(Native Method) ListActivity 1 package com.thickcrustdesigns.ufood; import java.util.ArrayList; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; public class CatogPage extends ListActivity { ListView listView1; Button btn_bk; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.definition_main); btn_bk = (Button) findViewById(R.id.btn_bk); listView1 = (ListView) findViewById(android.R.id.list); ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(); nvp.add(new BasicNameValuePair("request", "categories")); ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp); String[] defs = new String[jsondefs.size()]; for (int i = 0; i < jsondefs.size(); i++) { try { defs[i] = jsondefs.get(i).getString("Name"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } uFoodAdapter adapter = new uFoodAdapter(this, R.layout.definition_list, defs); listView1.setAdapter(adapter); ListView lv = getListView(); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView tv = (TextView) view; String p = tv.getText().toString(); Intent i = new Intent(getApplicationContext(), Results.class); i.putExtra("category", p); startActivity(i); } }); btn_bk.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { Intent i = new Intent(getApplicationContext(), UFoodAppActivity.class); startActivity(i); } }); } } **ListActivity 2** package com.thickcrustdesigns.ufood; import java.util.ArrayList; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.os.Bundle; import android.widget.ListView; public class Results extends ListActivity { ListView listView1; enum Category { Chicken, Beef, Chinese, Cocktails, Curry, Deserts, Fish, ForOne { public String toString() { return "For One"; } }, Lamb, LightBites { public String toString() { return "Light Bites"; } }, Pasta, Pork, Vegetarian } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.definition_main); listView1 = (ListView) findViewById(android.R.id.list); Bundle data = getIntent().getExtras(); String category = data.getString("category"); Category cat = Category.valueOf(category); String value = null; switch (cat) { case Chicken: value = "Chicken"; break; case Beef: value = "Beef"; break; case Chinese: value = "Chinese"; break; case Cocktails: value = "Cocktails"; break; case Curry: value = "Curry"; break; case Deserts: value = "Deserts"; break; case Fish: value = "Fish"; break; case ForOne: value = "ForOne"; break; case Lamb: value = "Lamb"; break; case LightBites: value = "LightBites"; break; case Pasta: value = "Pasta"; break; case Pork: value = "Pork"; break; case Vegetarian: value = "Vegetarian"; } ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(); nvp.add(new BasicNameValuePair("request", "category")); nvp.add(new BasicNameValuePair("cat", value)); ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp); String[] defs = new String[jsondefs.size()]; for (int i = 0; i < jsondefs.size(); i++) { try { defs[i] = jsondefs.get(i).getString("Name"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } uFoodAdapter adapter = new uFoodAdapter(this, R.layout.definition_list, defs); listView1.setAdapter(adapter); } } Request package com.thickcrustdesigns.ufood; 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.json.JSONArray; import org.json.JSONObject; import android.content.Context; import android.util.Log; import android.widget.Toast; public class Request { @SuppressWarnings("null") public static ArrayList<JSONObject> fetchData(Context context, ArrayList<NameValuePair> nvp) { ArrayList<JSONObject> listItems = new ArrayList<JSONObject>(); InputStream is = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://co350-11d.projects02.glos.ac.uk/php/database.php"); httppost.setEntity(new UrlEncodedFormEntity(nvp)); 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 String result = ""; try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); InputStream stream = null; StringBuilder sb = null; while ((result = reader.readLine()) != null) { sb.append(result + "\n"); } stream.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONArray jArray = new JSONArray(result); for (int i = 0; i < jArray.length(); i++) { JSONObject jo = jArray.getJSONObject(i); listItems.add(jo); } } catch (Exception e) { Toast.makeText(context.getApplicationContext(), "None Found!", Toast.LENGTH_LONG).show(); } return listItems; } } Any help would be grateful! Many Thanks EDIT Sorry very tired so missed out my 2nd ListActivity package com.thickcrustdesigns.ufood; import java.util.ArrayList; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.os.Bundle; import android.widget.ListView; public class Results extends ListActivity { ListView listView1; enum Category { Chicken, Beef, Chinese, Cocktails, Curry, Deserts, Fish, ForOne { public String toString() { return "For One"; } }, Lamb, LightBites { public String toString() { return "Light Bites"; } }, Pasta, Pork, Vegetarian } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.definition_main); listView1 = (ListView) findViewById(android.R.id.list); Bundle data = getIntent().getExtras(); String category = data.getString("category"); Category cat = Category.valueOf(category); String value = null; switch (cat) { case Chicken: value = "Chicken"; break; case Beef: value = "Beef"; break; case Chinese: value = "Chinese"; break; case Cocktails: value = "Cocktails"; break; case Curry: value = "Curry"; break; case Deserts: value = "Deserts"; break; case Fish: value = "Fish"; break; case ForOne: value = "ForOne"; break; case Lamb: value = "Lamb"; break; case LightBites: value = "LightBites"; break; case Pasta: value = "Pasta"; break; case Pork: value = "Pork"; break; case Vegetarian: value = "Vegetarian"; } ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>(); nvp.add(new BasicNameValuePair("request", "category")); nvp.add(new BasicNameValuePair("cat", value)); ArrayList<JSONObject> jsondefs = Request.fetchData(this, nvp); String[] defs = new String[jsondefs.size()]; for (int i = 0; i < jsondefs.size(); i++) { try { defs[i] = jsondefs.get(i).getString("Name"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } uFoodAdapter adapter = new uFoodAdapter(this, R.layout.definition_list, defs); listView1.setAdapter(adapter); } } Sorry again! Cheers guys!

    Read the article

  • Get data from MySQL to Android application

    - by Mona
    I want to get data from MySQL database using PHP and display it in Android activity. I code it and pass JSON Array but there is a problem i dont know how to connect to server and my all database is on local server. I code it Kindly tell me where i go wrong so I can get exact results. I'll be very thankful to you. My PHP code is: <?php $response = array(); require_once __DIR__ . '/db_connect.php'; $db = new DB_CONNECT(); if (isset($_GET["cid"])) { $cid = $_GET['cid']; // get a product from products table $result = mysql_query("SELECT *FROM my_task WHERE cid = $cid"); if (!empty($result)) { // check for empty result if (mysql_num_rows($result) > 0) { $result = mysql_fetch_array($result); $task = array(); $task["cid"] = $result["cid"]; $task["cus_name"] = $result["cus_name"]; $task["contact_number"] = $result["contact_number"]; $task["ticket_no"] = $result["ticket_no"]; $task["task_detail"] = $result["task_detail"]; // success $response["success"] = 1; // user node $response["task"] = array(); array_push($response["my_task"], $task); // echoing JSON response echo json_encode($response); } else { // no task found $response["success"] = 0; $response["message"] = "No product found"; // echo no users JSON echo json_encode($response); } } else { // no task found $response["success"] = 0; $response["message"] = "No product found"; echo json_encode($response); } } else { $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response);} ?> My Android code is: public class My_Task extends Activity { TextView cus_name_txt, contact_no_txt, ticket_no_txt, task_detail_txt; EditText attend_by_txtbx, cus_name_txtbx, contact_no_txtbx, ticket_no_txtbx, task_detail_txtbx; Button btnSave; Button btnDelete; String cid; // Progress Dialog private ProgressDialog tDialog; // Creating JSON Parser object JSONParser jParser = new JSONParser(); ArrayList<HashMap<String, String>> my_taskList; // single task url private static final String url_read_mytask = "http://198.168.0.29/mobile/read_My_Task.php"; // url to update product private static final String url_update_mytask = "http://198.168.0.29/mobile/update_mytask.php"; // url to delete product private static final String url_delete_mytask = "http://198.168.0.29/mobile/delete_mytask.php"; // JSON Node names private static String TAG_SUCCESS = "success"; private static String TAG_MYTASK = "my_task"; private static String TAG_CID = "cid"; private static String TAG_NAME = "cus_name"; private static String TAG_CONTACT = "contact_number"; private static String TAG_TICKET = "ticket_no"; private static String TAG_TASKDETAIL = "task_detail"; private static String attend_by_txt; // task JSONArray JSONArray my_task = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_task); cus_name_txt = (TextView) findViewById(R.id.cus_name_txt); contact_no_txt = (TextView)findViewById(R.id.contact_no_txt); ticket_no_txt = (TextView)findViewById(R.id.ticket_no_txt); task_detail_txt = (TextView)findViewById(R.id.task_detail_txt); attend_by_txtbx = (EditText)findViewById(R.id.attend_by_txt); attend_by_txtbx.setText(My_Task.attend_by_txt); Spinner severity = (Spinner) findViewById(R.id.severity_spinner); // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(this, R.array.Severity_array, android.R.layout.simple_dropdown_item_1line); // Specify the layout to use when the list of choices appears adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner severity.setAdapter(adapter3); // save button btnSave = (Button) findViewById(R.id.btnSave); btnDelete = (Button) findViewById(R.id.btnDelete); // getting product details from intent Intent i = getIntent(); // getting product id (pid) from intent cid = i.getStringExtra(TAG_CID); // Getting complete product details in background thread new GetProductDetails().execute(); // save button click event btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // starting background task to update product new SaveProductDetails().execute(); } }); // Delete button click event btnDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // deleting product in background thread new DeleteProduct().execute(); } }); } /** * Background Async Task to Get complete product details * */ class GetProductDetails extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); tDialog = new ProgressDialog(My_Task.this); tDialog.setMessage("Loading task details. Please wait..."); tDialog.setIndeterminate(false); tDialog.setCancelable(true); tDialog.show(); } /** * Getting product details in background thread * */ protected String doInBackground(String... params) { // updating UI from Background Thread runOnUiThread(new Runnable() { public void run() { // Check for success tag int success; try { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("cid", cid)); // getting product details by making HTTP request // Note that product details url will use GET request JSONObject json = JSONParser.makeHttpRequest( url_read_mytask, "GET", params); // check your log for json response Log.d("Single Task Details", json.toString()); // json success tag success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully received product details JSONArray my_taskObj = json .getJSONArray(TAG_MYTASK); // JSON Array // get first product object from JSON Array JSONObject my_task = my_taskObj.getJSONObject(0); // task with this cid found // Edit Text // display task data in EditText cus_name_txtbx = (EditText) findViewById(R.id.cus_name_txt); cus_name_txtbx.setText(my_task.getString(TAG_NAME)); contact_no_txtbx = (EditText) findViewById(R.id.contact_no_txt); contact_no_txtbx.setText(my_task.getString(TAG_CONTACT)); ticket_no_txtbx = (EditText) findViewById(R.id.ticket_no_txt); ticket_no_txtbx.setText(my_task.getString(TAG_TICKET)); task_detail_txtbx = (EditText) findViewById(R.id.task_detail_txt); task_detail_txtbx.setText(my_task.getString(TAG_TASKDETAIL)); } else { // task with cid not found } } catch (JSONException e) { e.printStackTrace(); } } }); return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once got all details tDialog.dismiss(); } } /** * Background Async Task to Save product Details * */ class SaveProductDetails extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); tDialog = new ProgressDialog(My_Task.this); tDialog.setMessage("Saving task ..."); tDialog.setIndeterminate(false); tDialog.setCancelable(true); tDialog.show(); } /** * Saving product * */ protected String doInBackground(String... args) { // getting updated data from EditTexts String cus_name = cus_name_txt.getText().toString(); String contact_no = contact_no_txt.getText().toString(); String ticket_no = ticket_no_txt.getText().toString(); String task_detail = task_detail_txt.getText().toString(); // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(TAG_CID, cid)); params.add(new BasicNameValuePair(TAG_NAME, cus_name)); params.add(new BasicNameValuePair(TAG_CONTACT, contact_no)); params.add(new BasicNameValuePair(TAG_TICKET, ticket_no)); params.add(new BasicNameValuePair(TAG_TASKDETAIL, task_detail)); // sending modified data through http request // Notice that update product url accepts POST method JSONObject json = JSONParser.makeHttpRequest(url_update_mytask, "POST", params); // check json success tag try { int success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully updated Intent i = getIntent(); // send result code 100 to notify about product update setResult(100, i); finish(); } else { // failed to update product } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once product uupdated tDialog.dismiss(); } } /***************************************************************** * Background Async Task to Delete Product * */ class DeleteProduct extends AsyncTask<String, String, String> { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); tDialog = new ProgressDialog(My_Task.this); tDialog.setMessage("Deleting Product..."); tDialog.setIndeterminate(false); tDialog.setCancelable(true); tDialog.show(); } /** * Deleting product * */ protected String doInBackground(String... args) { // Check for success tag int success; try { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("cid", cid)); // getting product details by making HTTP request JSONObject json = JSONParser.makeHttpRequest( url_delete_mytask, "POST", params); // check your log for json response Log.d("Delete Task", json.toString()); // json success tag success = json.getInt(TAG_SUCCESS); if (success == 1) { // product successfully deleted // notify previous activity by sending code 100 Intent i = getIntent(); // send result code 100 to notify about product deletion setResult(100, i); finish(); } } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once product deleted tDialog.dismiss(); } } public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { // An item was selected. You can retrieve the selected item using // parent.getItemAtPosition(pos) } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback } } My JSONParser code is: public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public static 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; my all database is in localhost and it is not opening an activity. displays an error "Stopped unexpectedly":( How can i get exact results. Kindly guide me

    Read the article

  • What's new in Xamarin and iOS7 - webinar

    - by Wallym
    I recently did an online webinar regarding the new iOS7 and Xamarin.  In it, I covered the basics of what is new in iOS7 along with what is new in Xamarin's developer platform.  Please take some time and view this webinar.  The items that were covered include:What's new in iOS7.The XCode Design Surface.An example showing new iOS7 View Animations.What's new with Xamarin and async, await, and HttpClient.A demo of Razor Templating.The Xamarin.iOS Plugin for Visual Studio.  ** The video only works in Windows.  I don't control the content, so I have to go with what I am given. :-( **

    Read the article

  • Token based Authentication for WCF HTTP/REST Services: The Client

    - by Your DisplayName here!
    If you wondered how a client would have to look like to work with the authentication framework, it is pretty straightfoward: Request a token Put that token on the authorization header (along with a registered scheme) and make the service call e.g.: var oauth2 = new OAuth2Client(_oauth2Address); var swt = oauth2.RequestAccessToken( "username", "password", _baseAddress.AbsoluteUri);   var client = new HttpClient { BaseAddress = _baseAddress }; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", swt); var response = client.Get("identity"); response.EnsureSuccessStatusCode(); HTH

    Read the article

  • Managing common code on Windows 7 (.NET) and Windows 8 (WinRT)

    - by ryanabr
    Recent announcements regarding Windows Phone 8 and the fact that it will have the WinRT behind it might make some of this less painful but I  discovered the "XmlDocument" object is in a new location in WinRT and is almost the same as it's brother in .NET System.Xml.XmlDocument (.NET) Windows.Data.Xml.Dom.XmlDocument (WinRT) The problem I am trying to solve is how to work with both types in the code that performs the same task on both Windows Phone 7 and Windows 8 platforms. The first thing I did was define my own XmlNode and XmlNodeList classes that wrap the actual Microsoft objects so that by using the "#if" compiler directive either work with the WinRT version of the type, or the .NET version from the calling code easily. public class XmlNode     { #if WIN8         public Windows.Data.Xml.Dom.IXmlNode Node { get; set; }         public XmlNode(Windows.Data.Xml.Dom.IXmlNode xmlNode)         {             Node = xmlNode;         } #endif #if !WIN8 public System.Xml.XmlNode Node { get; set ; } public XmlNode(System.Xml.XmlNode xmlNode)         {             Node = xmlNode;         } #endif     } public class XmlNodeList     { #if WIN8         public Windows.Data.Xml.Dom.XmlNodeList List { get; set; }         public int Count {get {return (int)List.Count;}}         public XmlNodeList(Windows.Data.Xml.Dom.XmlNodeList list)         {             List = list;         } #endif #if !WIN8 public System.Xml.XmlNodeList List { get; set ; } public int Count { get { return List.Count;}} public XmlNodeList(System.Xml.XmlNodeList list)         {             List = list;        } #endif     } From there I can then use my XmlNode and XmlNodeList in the calling code with out having to clutter the code with all of the additional #if switches. The challenge after this was the code that worked directly with the XMLDocument object needed to be seperate on both platforms since the method for populating the XmlDocument object is completly different on both platforms. To solve this issue. I made partial classes, one partial class for .NET and one for WinRT. Both projects have Links to the Partial Class that contains the code that is the same for the majority of the class, and the partial class contains the code that is unique to the version of the XmlDocument. The files with the little arrow in the lower left corner denotes 'linked files' and are shared in multiple projects but only exist in one location in source control. You can see that the _Win7 partial class is included directly in the project since it include code that is only for the .NET platform, where as it's cousin the _Win8 (not pictured above) has all of the code specific to the _Win8 platform. In the _Win7 partial class is this code: public partial class WUndergroundViewModel     { public static WUndergroundData GetWeatherData( double lat, double lng)         { WUndergroundData data = new WUndergroundData();             System.Net. WebClient c = new System.Net. WebClient(); string req = "http://api.wunderground.com/api/xxx/yesterday/conditions/forecast/q/[LAT],[LNG].xml" ;             req = req.Replace( "[LAT]" , lat.ToString());             req = req.Replace( "[LNG]" , lng.ToString()); XmlDocument doc = new XmlDocument();             doc.Load(c.OpenRead(req)); foreach (XmlNode item in doc.SelectNodes("/response/features/feature" ))             { switch (item.Node.InnerText)                 { case "yesterday" :                         ParseForecast( new FishingControls.XmlNodeList (doc.SelectNodes( "/response/forecast/txt_forecast/forecastdays/forecastday" )), new FishingControls.XmlNodeList (doc.SelectNodes( "/response/forecast/simpleforecast/forecastdays/forecastday" )), data); break ; case "conditions" :                         ParseCurrent( new FishingControls.XmlNode (doc.SelectSingleNode("/response/current_observation" )), data); break ; case "forecast" :                         ParseYesterday( new FishingControls.XmlNodeList (doc.SelectNodes( "/response/history/observations/observation" )),data); break ;                 }             } return data;         }     } in _win8 partial class is this code: public partial class WUndergroundViewModel     { public async static Task< WUndergroundData > GetWeatherData(double lat, double lng)         { WUndergroundData data = new WUndergroundData (); HttpClient c = new HttpClient (); string req = "http://api.wunderground.com/api/xxxx/yesterday/conditions/forecast/q/[LAT],[LNG].xml" ;             req = req.Replace( "[LAT]" , lat.ToString());             req = req.Replace( "[LNG]" , lng.ToString()); HttpResponseMessage msg = await c.GetAsync(req); string stream = await msg.Content.ReadAsStringAsync(); XmlDocument doc = new XmlDocument ();             doc.LoadXml(stream, null); foreach ( IXmlNode item in doc.SelectNodes("/response/features/feature" ))             { switch (item.InnerText)                 { case "yesterday" :                         ParseForecast( new FishingControls.XmlNodeList (doc.SelectNodes( "/response/forecast/txt_forecast/forecastdays/forecastday" )), new FishingControls.XmlNodeList (doc.SelectNodes( "/response/forecast/simpleforecast/forecastdays/forecastday" )), data); break; case "conditions" :                         ParseCurrent( new FishingControls.XmlNode (doc.SelectSingleNode("/response/current_observation" )), data); break; case "forecast" :                         ParseYesterday( new FishingControls.XmlNodeList (doc.SelectNodes( "/response/history/observations/observation")), data); break;                 }             } return data;         }     } Summary: This method allows me to have common 'business' code for both platforms that is pretty clean, and I manage the technology differences separately. Thank you tostringtheory for your suggestion, I was considering that approach.

    Read the article

  • Retrieving Json Array

    - by Rahul Varma
    Hi, I am trying to retrieve the values from the following url: http://rentopoly.com/ajax.php?query=Bo. I want to get the values of all the suggestions to be displayed in a list view one by one. This is how i want to do... public class AlertsAdd { public ArrayList<JSONObject> retrieveJSONArray(String urlString) { String result = queryRESTurl(urlString); ArrayList<JSONObject> ALERTS = new ArrayList<JSONObject>(); if (result != null) { try { JSONObject json = new JSONObject(result); JSONArray alertsArray = json.getJSONArray("suggestions"); for (int a = 0; a < alertsArray.length(); a++) { JSONObject alertitem = alertsArray.getJSONObject(a); ALERTS.add(alertitem); } return ALERTS; } catch (JSONException e) { Log.e("JSON", "There was an error parsing the JSON", e); } } JSONObject myObject = new JSONObject(); try { myObject.put("suggestions",myObject.getJSONArray("suggestions")); ALERTS.add(myObject); } catch (JSONException e1) { Log.e("JSON", "There was an error creating the JSONObject", e1); } return ALERTS; } private String queryRESTurl(String url) { // URLConnection connection; HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response; try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); String result = convertStreamToString(instream); instream.close(); return result; } } catch (ClientProtocolException e) { Log.e("REST", "There was a protocol based error", e); } catch (IOException e) { Log.e("REST", "There was an IO Stream related error", e); } return null; } /** * To convert the InputStream to String we use the * BufferedReader.readLine() method. We iterate until the BufferedReader * return null which means there's no more data to read. Each line will * appended to a StringBuilder and returned as String. */ private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } } Here's the adapter code... public class AlertsAdapter extends ArrayAdapter<JSONObject> { public AlertsAdapter(Activity activity, List<JSONObject> alerts) { super(activity, 0, alerts); } @Override public View getView(int position, View convertView, ViewGroup parent) { Activity activity = (Activity) getContext(); LayoutInflater inflater = activity.getLayoutInflater(); View rowView = inflater.inflate(R.layout.list_text, null); JSONObject imageAndText = getItem(position); TextView textView = (TextView) rowView.findViewById(R.id.last_build_stat); try { textView.setText((String)imageAndText.get("suggestions")); } catch (JSONException e) { textView.setText("JSON Exception"); } return rowView; } } Here's the logcat... 04-30 13:09:46.656: INFO/ActivityManager(584): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.WorldToyota/.Alerts } 04-30 13:09:50.417: ERROR/JSON(924): There was an error parsing the JSON 04-30 13:09:50.417: ERROR/JSON(924): org.json.JSONException: JSONArray[0] is not a JSONObject. 04-30 13:09:50.417: ERROR/JSON(924): at org.json.JSONArray.getJSONObject(JSONArray.java:268) 04-30 13:09:50.417: ERROR/JSON(924): at com.WorldToyota.AlertsAdd.retrieveJSONArray(AlertsAdd.java:30) 04-30 13:09:50.417: ERROR/JSON(924): at com.WorldToyota.Alerts.onCreate(Alerts.java:20) 04-30 13:09:50.417: ERROR/JSON(924): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123) 04-30 13:09:50.417: ERROR/JSON(924): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364) 04-30 13:09:50.417: ERROR/JSON(924): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417) 04-30 13:09:50.417: ERROR/JSON(924): at android.app.ActivityThread.access$2100(ActivityThread.java:116) 04-30 13:09:50.417: ERROR/JSON(924): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 04-30 13:09:50.417: ERROR/JSON(924): at android.os.Handler.dispatchMessage(Handler.java:99) 04-30 13:09:50.417: ERROR/JSON(924): at android.os.Looper.loop(Looper.java:123) 04-30 13:09:50.417: ERROR/JSON(924): at android.app.ActivityThread.main(ActivityThread.java:4203) 04-30 13:09:50.417: ERROR/JSON(924): at java.lang.reflect.Method.invokeNative(Native Method) 04-30 13:09:50.417: ERROR/JSON(924): at java.lang.reflect.Method.invoke(Method.java:521) 04-30 13:09:50.417: ERROR/JSON(924): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 04-30 13:09:50.417: ERROR/JSON(924): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549) 04-30 13:09:50.417: ERROR/JSON(924): at dalvik.system.NativeStart.main(Native Method) 04-30 13:09:50.688: ERROR/JSON(924): There was an error creating the JSONObject 04-30 13:09:50.688: ERROR/JSON(924): org.json.JSONException: JSONObject["suggestions"] not found. 04-30 13:09:50.688: ERROR/JSON(924): at org.json.JSONObject.get(JSONObject.java:287) 04-30 13:09:50.688: ERROR/JSON(924): at org.json.JSONObject.getJSONArray(JSONObject.java:362) 04-30 13:09:50.688: ERROR/JSON(924): at com.WorldToyota.AlertsAdd.retrieveJSONArray(AlertsAdd.java:41) 04-30 13:09:50.688: ERROR/JSON(924): at com.WorldToyota.Alerts.onCreate(Alerts.java:20) 04-30 13:09:50.688: ERROR/JSON(924): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123) 04-30 13:09:50.688: ERROR/JSON(924): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364) 04-30 13:09:50.688: ERROR/JSON(924): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417) 04-30 13:09:50.688: ERROR/JSON(924): at android.app.ActivityThread.access$2100(ActivityThread.java:116) 04-30 13:09:50.688: ERROR/JSON(924): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794) 04-30 13:09:50.688: ERROR/JSON(924): at android.os.Handler.dispatchMessage(Handler.java:99) 04-30 13:09:50.688: ERROR/JSON(924): at android.os.Looper.loop(Looper.java:123) 04-30 13:09:50.688: ERROR/JSON(924): at android.app.ActivityThread.main(ActivityThread.java:4203) 04-30 13:09:50.688: ERROR/JSON(924): at java.lang.reflect.Method.invokeNative(Native Method) 04-30 13:09:50.688: ERROR/JSON(924): at java.lang.reflect.Method.invoke(Method.java:521) 04-30 13:09:50.688: ERROR/JSON(924): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 04-30 13:09:50.688: ERROR/JSON(924): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549) 04-30 13:09:50.688: ERROR/JSON(924): at dalvik.system.NativeStart.main(Native Method) Plz help me parsing this script and displaying the values in list format....

    Read the article

  • Android Mediaplayer: setDataSource issue for downloaded media file

    - by Erik
    I have an application that will record and play audio files. Some of the audio files are downloaded using simple standard http downloads using httpclient. It worked like a charm for a long time. Now all of a sudden I cannot play the files I download. It fails with this stack. I store the files on the SDCard and I experience the problem both on a handset and a USB connected device. I have checked that the downloaded file is cool on the server, and I can play it without any issues. These are the code snippets I use ( I know that recordingFile is a valid path for the file). // inside the activity class private void playRecording() throws IOException{ File recordingFile = new File(recordingFileName); FileInputStream recordingInputStream = new FileInputStream(recordingFile); audioMediaPlayer.playAudio(recordingInputStream); } Here is the media player code: // inside my media player class which handles the recordings public void playAudio(FileInputStream audioInputStream) throws IOException { mediaPlayer.reset(); mediaPlayer.setDataSource(audioInputStream.getFD()); mediaPlayer.prepare(); mediaPlayer.start(); } Here is the exception: E/MediaPlayerService( 555): offset error E/MediaPlayer( 786): Unable to to create media player W/System.err( 786): java.io.IOException: setDataSourceFD failed.: status=0x80000000 W/System.err( 786): at android.media.MediaPlayer.setDataSource(Native Method) W/System.err( 786): at android.media.MediaPlayer.setDataSource(MediaPlayer.java:632) W/System.err( 786): at net.xxx.xxx.AudioMediaPlayer.playAudio(AudioMediaPlayer.java:69) W/System.err( 786): at net.xxx.xxx.Downloads.playRecording(Downloads.java:299) W/System.err( 786): at net.xxx.xxx.Downloads.access$0(Downloads.java:294) W/System.err( 786): at net.xxx.xxx.Downloads$1.onClick(Downloads.java:135) I have tried seeking some answer of the offset error, but not really clear what this issue might be. PS I download the file with this code: public FileOutputStream executeHttpGet(FileOutputStream fileOutputStream) throws ClientProtocolException, IOException{ try { // Execute HTTP Post Request httpResponse = httpClient.execute(httpPost, localContext); int status = httpResponse.getStatusLine().getStatusCode(); // we assume that the response body contains the error message if (status != HttpStatus.SC_OK) { ByteArrayOutputStream ostream = new ByteArrayOutputStream(); httpResponse.getEntity().writeTo(ostream); fileOutputStream = null; } else { InputStream content = httpResponse.getEntity().getContent(); byte[] buffer = new byte[1024]; int len = 0; while ( (len = content.read(buffer)) > 0 ) { fileOutputStream.write(buffer,0, len); } fileOutputStream.close(); content.close(); // this will also close the connection } } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); fileOutputStream = null; } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); fileOutputStream = null; } return fileOutputStream; }

    Read the article

  • Retrieve EF4 POCOs using WCF REST services starter kit

    - by muruge
    I am using WCF REST service (GET method) to retrieve my EF4 POCOs. The service seem to work just fine. When I query the uri in my browser I get the results as expected. In my client application I am trying to use WCF REST Starter Kit's HTTPExtension method - ReadAsDataContract() to convert the result back into my POCO. This works fine when the POCO's navigation property is a single object of related POCO. The problem is when the navigation property is a collection of related POCOs. The ReadAsDataContract() method throws an exception with message "Object reference not set to an instance of an object." Below are my POCOs. [DataContract(Namespace = "", Name = "Trip")] public class Trip { [DataMember(Order = 1)] public virtual int TripID { get; set; } [DataMember(Order = 2)] public virtual int RegionID { get; set; } [DataMember(Order = 3)] public virtual System.DateTime BookingDate { get; set; } [DataMember(Order = 4)] public virtual Region Region { // removed for brevity } } [DataContract(Namespace = "", Name = "Region")] public class Region { [DataMember(Order = 1)] public virtual int RegionID { get; set; } [DataMember(Order = 2)] public virtual string RegionCode { get; set; } [DataMember(Order = 3)] public virtual FixupCollection<Trip> Trips { // removed for brevity } } [CollectionDataContract(Namespace = "", Name = "{0}s", ItemName = "{0}")] [Serializable] public class FixupCollection<T> : ObservableCollection<T> { protected override void ClearItems() { new List<T>(this).ForEach(t => Remove(t)); } protected override void InsertItem(int index, T item) { if (!this.Contains(item)) { base.InsertItem(index, item); } } } And this is how I am trying retrieve a Region POCO. static void GetRegion() { string uri = "http://localhost:8080/TripService/Regions?id=1"; HttpClient client = new HttpClient(uri); using (HttpResponseMessage response = client.Get(uri)) { Region region; response.EnsureStatusIsSuccessful(); try { region = response.Content.ReadAsDataContract<Region>(); // this line throws exception because Region returns a collection of related trips Console.WriteLine(region.RegionName); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } Would appreciate any pointers.

    Read the article

  • Problem in JSF2 with client-side state saving and serialization

    - by marcel
    I have a problem in JSF2 with client side state saving and serialization. I have created a page with a full description and a small class diagram: http://tinyurl.com/jsf2serial. For the client-side state saving I have to implement Serializable at the classes Search, BackingBean and Connection. The exception that was thrown is: java.io.NotSerializableException: org.apache.commons.httpclient.HttpClient at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1156) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326) at java.util.HashMap.writeObject(HashMap.java:1001) at sun.reflect.GeneratedMethodAccessor80.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1461) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1509) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1474) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.writeArray(ObjectOutputStream.java:1338) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1146) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326) at java.util.HashMap.writeObject(HashMap.java:1001) at sun.reflect.GeneratedMethodAccessor80.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:945) at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1461) at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1392) at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1150) at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326) at com.sun.faces.renderkit.ClientSideStateHelper.doWriteState(ClientSideStateHelper.java:293) at com.sun.faces.renderkit.ClientSideStateHelper.writeState(ClientSideStateHelper.java:167) at com.sun.faces.renderkit.ResponseStateManagerImpl.writeState(ResponseStateManagerImpl.java:123) at com.sun.faces.application.StateManagerImpl.writeState(StateManagerImpl.java:155) at com.sun.faces.application.view.WriteBehindStateWriter.flushToWriter(WriteBehindStateWriter.java:221) at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:397) at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:126) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:127) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Thread.java:637) Maybe this is a problem of my design, because I am new in developing Java webapps.

    Read the article

  • 'SSL not supported' when calling https web service in Ruby

    - by shaleo
    I am trying to run the following code to call a webservice from ruby but get an error 'SSL not supported'. I have httpclient 2.1.5.2 installed. require 'soap/wsdlDriver' def validate_certificate(is_ok, ctx) cert = ctx.current_cert unless (cert.subject.to_s == cert.issuer.to_s) #check the server certificate only is_ok &&= File.open(file_name).read == ctx.current_cert.to_pem end is_ok end def test_webservice wsdl = "https://.../service.wsdl" driver = SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver driver.options['protocol.http.ssl_config.verify_callback'] = method(:validate_certificate) driver.method(params) end

    Read the article

  • Spring - singleton problem - No bean named '....' found

    - by lisak
    Hey, I can't figure out what is wrong with this beans definition. I'm getting this error http://pastebin.com/ecn5SWLa . Especially the 14th log message is interesting. This is my app-context file http://pastebin.com/dreubpRY httpParams is a singleton which is set up in httpParamBean and then used by tsccManager and httpClient. The various depends-on settings is a result of my effort to figure it out.

    Read the article

  • problem to create session of facebook

    - by khoyendra
    try { HttpClient http = new HttpClient(); http.setParams(new HttpClientParams()); //http.getHostConfiguration().setHost("http://www.facebook.com/"); http.setState(new HttpState()); String api_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; String secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // String appId=124812364218050; //http://www.facebook.com/developers/editapp.php?app_id=124812364218050 FacebookRestClient client = new FacebookRestClient(api_key, secret); client.setIsDesktop(true); // String sessionKey = request.getParameter(FacebookParam.SESSION_KEY.toString()); // boolean b = client.users_setStatus("This is a test..."); // System.out.println("User Status RESULT : " + b); String token = client.auth_createToken(); final String loginId = "http://www.facebook.com/login.php"; GetMethod get = new GetMethod(loginId + "?api_key=" + api_key + "&v=1.0&auth_token=" +token); System.out.println("Get="+get); http.executeMethod(get); PostMethod post = new PostMethod(loginId); post.addParameter(new NameValuePair("api_key", api_key)); post.addParameter(new NameValuePair("v", "1.0")); post.addParameter(new NameValuePair("auth_token", token)); post.addParameter(new NameValuePair("fbconnect","true")); post.addParameter(new NameValuePair("return_session","true")); post.addParameter(new NameValuePair("session_key_only","true")); post.addParameter(new NameValuePair("req_perms","read_stream,publish_stream")); post.addParameter(new NameValuePair("email", email)); post.addParameter(new NameValuePair("pass", password)); System.out.println("Token ="+token); int postStatus = http.executeMethod(post); System.out.println("Response : " + postStatus); session = client.auth_getSession(token); // Here I am getting error System.out.println("Session string: " + session); long userid = client.users_getLoggedInUser(); System.out.println("User Id is : " + userid); } catch (Exception e) { e.printStackTrace(); } please solve my problem i cannot create session of facebook.

    Read the article

  • while uploading image I get errors in logcat

    - by al0ne evenings
    I am uploading image and also sending some parameters with it. I am getting errors in my logcat while doing so. Here is my code public class Camera extends Activity { ImageView ivUserImage; Button bUpload; Intent i; int CameraResult = 0; Bitmap bmp; public String globalUID; UserFunctions userFunctions; String photoName; InputStream is; int serverResponseCode = 0; ProgressDialog dialog = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.camera); userFunctions = new UserFunctions(); globalUID = getIntent().getExtras().getString("globalUID"); Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show(); ivUserImage = (ImageView)findViewById(R.id.ivUserImage); bUpload = (Button)findViewById(R.id.bUpload); openCamera(); } private void openCamera() { i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(i, CameraResult); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_OK) { //set image taken from camera on ImageView Bundle extras = data.getExtras(); bmp = (Bitmap) extras.get("data"); ivUserImage.setImageBitmap(bmp); //Create new Cursor to obtain the file Path for the large image String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA }; String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC"; //final String photoName = MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME; Cursor myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort); try { myCursor.moveToFirst(); //This will actually give you the file path location of the image. final String largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA)); //final String photoName = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME)); //Log.e("URI", largeImagePath); File f = new File("" + largeImagePath); photoName = f.getName(); bUpload.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dialog = ProgressDialog.show(Camera.this, "", "Uploading file...", true); new Thread(new Runnable() { public void run() { runOnUiThread(new Runnable() { public void run() { //tv.setText("uploading started....."); Toast.makeText(getBaseContext(), "File is uploading...", Toast.LENGTH_LONG).show(); } }); if(imageUpload(globalUID, largeImagePath)) { Toast.makeText(getApplicationContext(), "Image uploaded", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Error uploading image", Toast.LENGTH_LONG).show(); } //Log.e("Response: ", response); //System.out.println("RES : " + response); } }).start(); } }); } finally { myCursor.close(); } //Uri uriLargeImage = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(imageId)); //String imageUrl = getRealPathFromURI(uriLargeImage); } } public boolean imageUpload(String uid, String imagepath) { boolean success = false; //Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); Bitmap bitmapOrg = BitmapFactory.decodeFile(imagepath); ByteArrayOutputStream bao = new ByteArrayOutputStream(); bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao); byte [] ba = bao.toByteArray(); String ba1=Base64.encodeToString(ba, 0); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("image",ba1)); nameValuePairs.add(new BasicNameValuePair("uid", uid)); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.example.info/androidfileupload/index.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if(response != null) { success = true; } is = entity.getContent(); } catch(Exception e) { Log.e("log_tag", "Error in http connection "+e.toString()); } dialog.dismiss(); return success; } Here is my logcat 06-23 11:54:48.555: E/AndroidRuntime(30601): FATAL EXCEPTION: Thread-11 06-23 11:54:48.555: E/AndroidRuntime(30601): java.lang.OutOfMemoryError 06-23 11:54:48.555: E/AndroidRuntime(30601): at java.lang.String.<init>(String.java:513) 06-23 11:54:48.555: E/AndroidRuntime(30601): at java.lang.AbstractStringBuilder.toString(AbstractStringBuilder.java:650) 06-23 11:54:48.555: E/AndroidRuntime(30601): at java.lang.StringBuilder.toString(StringBuilder.java:664) 06-23 11:54:48.555: E/AndroidRuntime(30601): at org.apache.http.client.utils.URLEncodedUtils.format(URLEncodedUtils.java:170) 06-23 11:54:48.555: E/AndroidRuntime(30601): at org.apache.http.client.entity.UrlEncodedFormEntity.<init>(UrlEncodedFormEntity.java:71) 06-23 11:54:48.555: E/AndroidRuntime(30601): at com.zafar.login.Camera.imageUpload(Camera.java:155) 06-23 11:54:48.555: E/AndroidRuntime(30601): at com.zafar.login.Camera$1$1.run(Camera.java:119) 06-23 11:54:48.555: E/AndroidRuntime(30601): at java.lang.Thread.run(Thread.java:1019) 06-23 11:54:53.960: E/WindowManager(30601): Activity com.zafar.login.DashboardActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@405db540 that was originally added here 06-23 11:54:53.960: E/WindowManager(30601): android.view.WindowLeaked: Activity com.zafar.login.DashboardActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@405db540 that was originally added here 06-23 11:54:53.960: E/WindowManager(30601): at android.view.ViewRoot.<init>(ViewRoot.java:266) 06-23 11:54:53.960: E/WindowManager(30601): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:174) 06-23 11:54:53.960: E/WindowManager(30601): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:117) 06-23 11:54:53.960: E/WindowManager(30601): at android.view.Window$LocalWindowManager.addView(Window.java:424) 06-23 11:54:53.960: E/WindowManager(30601): at android.app.Dialog.show(Dialog.java:241) 06-23 11:54:53.960: E/WindowManager(30601): at android.app.ProgressDialog.show(ProgressDialog.java:107) 06-23 11:54:53.960: E/WindowManager(30601): at android.app.ProgressDialog.show(ProgressDialog.java:90) 06-23 11:54:53.960: E/WindowManager(30601): at com.zafar.login.Camera$1.onClick(Camera.java:110) 06-23 11:54:53.960: E/WindowManager(30601): at android.view.View.performClick(View.java:2538) 06-23 11:54:53.960: E/WindowManager(30601): at android.view.View$PerformClick.run(View.java:9152) 06-23 11:54:53.960: E/WindowManager(30601): at android.os.Handler.handleCallback(Handler.java:587) 06-23 11:54:53.960: E/WindowManager(30601): at android.os.Handler.dispatchMessage(Handler.java:92) 06-23 11:54:53.960: E/WindowManager(30601): at android.os.Looper.loop(Looper.java:130) 06-23 11:54:53.960: E/WindowManager(30601): at android.app.ActivityThread.main(ActivityThread.java:3691) 06-23 11:54:53.960: E/WindowManager(30601): at java.lang.reflect.Method.invokeNative(Native Method) 06-23 11:54:53.960: E/WindowManager(30601): at java.lang.reflect.Method.invoke(Method.java:507) 06-23 11:54:53.960: E/WindowManager(30601): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907) 06-23 11:54:53.960: E/WindowManager(30601): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) 06-23 11:54:53.960: E/WindowManager(30601): at dalvik.system.NativeStart.main(Native Method) 06-23 11:54:55.190: I/Process(30601): Sending signal. PID: 30601 SIG: 9

    Read the article

  • SOAP logging axis2

    - by salcin
    Using axis1 it is possible to log incoming/outgoing soap messages by adding logging on HTTPSender in log4j.properties. After migrating to axis2 (version 1.4.1) I have a hard time figuring out how to accomplish the same kind of logging. I have tried to add logging on the axis2 package and org.apache.commons.httpclient but no logging is provided. Any ideas? TIA

    Read the article

  • Does WCF make the consumption of Restful web services trivial?

    - by Steve Weet
    I have an ASP.net application that currently consumes SOAP web services. This platform is targeted at .net 2.0 and I use Visual Studio Professional 2005 to maintain it. I now have a requirement to consume a number of restful web service within the same application. Is the consumption of Restful web services with WCF so trivial, compared to using HttpClient that it is worth the cost and time of upgrading to Visual Studio 2008 and .Net 3.5 framework

    Read the article

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