Doing HTTP Post with Android

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

Doing HTTP Post with Android

Postby plusminus » Thu Jan 10, 2008 10:26 pm

Doing HTTP Post with Android


What you will learn: You will learn how to do HTTP Post from within Android.

:?: Problems/Questions: Write them right below...

Difficulty: 2 of 5 :)

What it will look like:
Image


Description:
0.) HTTP is a request-response protocol. Various types of requests are possible, each identified by a different HTTP method. Here we will use the POST-Method.

1.) So we will once again start, where all Activities start. We will do some simple preparation first:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.         @Override
  2.         public void onCreate(Bundle icicle) {
  3.                 super.onCreate(icicle);
  4.  
  5.                 /* Create a new HTTP-RequestQueue. */
  6.                 android.net.http.RequestQueue rQueue = new RequestQueue(this);
  7.                
  8.                 /* Prepare the Post-Text we are going to send. */
  9.                 String POSTText = null;
  10.                 try {
  11.                         POSTText = "mydata=" + URLEncoder.encode("HELLO, ANDROID HTTPPostExample - by anddev.org", "UTF-8");
  12.                 } catch (UnsupportedEncodingException e) {
  13.                         return;
  14.                 }
  15.                 /* And put the encoded bytes into an BAIS,
  16.                  * where a function later can READ bytes from. */
  17.                 byte[] POSTbytes = POSTText.getBytes();
  18.                 ByteArrayInputStream baos = new ByteArrayInputStream(POSTbytes);
Parsed in 0.034 seconds, using GeSHi 1.0.8.4

2.) Preparation is done now, now we will do the interesting stuff:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 /* Create a header-hashmap */
  2.                 Map<String, String> headers = new HashMap<String, String>();
  3.                 /* and put the Default-Encoding for html-forms to it. */
  4.                 headers.put("Content-Type", "application/x-www-form-urlencoded");
  5.                
  6.                 /* Create a new EventHandler defined above, to handle what gets returned. */
  7.                 MyEventHandler myEvH = new MyEventHandler(this);
Parsed in 0.031 seconds, using GeSHi 1.0.8.4

:idea: MyEventHandler is described in step 5.)

3.) I prepared a very simple php-file on my server, which will simply echo the 'mydata' variable posted to it:
Syntax: [ Download ] [ Hide ]
Using php Syntax Highlighting
  1.                  <?php
  2.                                 echo "POSTed data: '".$_POST['mydata']."'";
  3.                  ?>
Parsed in 0.062 seconds, using GeSHi 1.0.8.4

4.) So we will call the queueRequest of our RequestQueue with the following parameters:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. "http://www.anddev.org/postresponse.php",  // The location of the php-file
  2. "POST", // The Request-'Mode'
  3. headers, // The Header which tells we will have some POST-vars
  4. myEvH, // our eventhandler
  5. baos, // our POST-String(converted to bytes) and ready to be sent
  6. POSTbytes.length, // amount of the bytes in 'baos' to be sent
  7. false // dunno <img src="http://www.anddev.org/images/smilies/hmm.png" alt=":?" title="Confused" />
Parsed in 0.036 seconds, using GeSHi 1.0.8.4

So as a real implementated call it looks like this:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 /* Calls a php-file I prepared. It looks like:
  2.                  * <?php
  3.                  *              echo "POSTed data: '".$_POST['data']."'";
  4.                  * ?>*/
  5.                 rQueue.queueRequest("http://www.anddev.org/postresponse.php", "POST",
  6.                                 headers, myEvH, baos, POSTbytes.length,false);
  7.  
  8.                 /* Wait until the request is complete.*/
  9.                 rQueue.waitUntilComplete();
  10.         }
Parsed in 0.036 seconds, using GeSHi 1.0.8.4


5.) The last thing we have is a small nearly dummy-class, the MyEventHandler, which simple reacts on events that occur during the "answer" of the requested url called. There basically are just two functions that actually do something:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 public void data(byte[] bytes, int len) {
  2.                         baf.append(bytes, 0, len); // Add received data to a buffer }
  3.  
  4.                 public void endData() {
  5.                         String text = new String(baf.toByteArray()); // Conert Buffer to String
  6.                         myShowNotificationAndLog("Data loaded: n" + text); // Log what was returned }
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


Thats it :)


The Full Source:

"/src/your_package_structure/HTTPPostExample.java"
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package org.anddev.android.webstuff;
  2.  
  3. import java.io.ByteArrayInputStream;
  4. import java.io.UnsupportedEncodingException;
  5. import java.net.URLEncoder;
  6. import java.util.HashMap;
  7. import java.util.Iterator;
  8. import java.util.Map;
  9.  
  10. import org.apache.http.util.ByteArrayBuffer;
  11.  
  12. import android.app.Activity;
  13. import android.app.NotificationManager;
  14. import android.net.http.EventHandler;
  15. import android.net.http.Headers;
  16. import android.net.http.RequestQueue;
  17. import android.net.http.SslCertificate;
  18. import android.os.Bundle;
  19. import android.util.Log;
  20.  
  21. public class HTTPPostExample extends Activity {
  22.  
  23.         // ===========================================================
  24.         // Fields
  25.         // ===========================================================
  26.        
  27.         private final String DEBUG_TAG = "httpPostExample";
  28.  
  29.         // ===========================================================
  30.         // 'Constructors'
  31.         // ===========================================================
  32.  
  33.         @Override
  34.         public void onCreate(Bundle icicle) {
  35.                 super.onCreate(icicle);
  36.  
  37.                 /* Create a new HTTP-RequestQueue. */
  38.                 android.net.http.RequestQueue rQueue = new RequestQueue(this);
  39.                
  40.                 /* Prepare the Post-Text we are going to send. */
  41.                 String POSTText = null;
  42.                 try {
  43.                         POSTText = "mydata=" + URLEncoder.encode("HELLO, ANDROID HTTPPostExample - by anddev.org", "UTF-8");
  44.                 } catch (UnsupportedEncodingException e) {
  45.                         return;
  46.                 }
  47.                 /* And put the encoded bytes into an BAIS,
  48.                  * where a function later can read bytes from. */
  49.                 byte[] POSTbytes = POSTText.getBytes();
  50.                 ByteArrayInputStream baos = new ByteArrayInputStream(POSTbytes);
  51.                
  52.                 /* Create a header-hashmap */
  53.                 Map<String, String> headers = new HashMap<String, String>();
  54.                 /* and put the Default-Encoding for html-forms to it. */
  55.                 headers.put("Content-Type", "application/x-www-form-urlencoded");
  56.                
  57.                 /* Create a new EventHandler defined above, to handle what gets returned. */
  58.                 MyEventHandler myEvH = new MyEventHandler(this);
  59.  
  60.                 /* Now we call a php-file I prepared. It is exactly this:
  61.                  * <?php
  62.                  *              echo "POSTed data: '".$_POST['data']."'";
  63.                  * ?>*/
  64.                 rQueue.queueRequest("http://www.anddev.org/postresponse.php", "POST",
  65.                                 headers, myEvH, baos, POSTbytes.length,false);
  66.  
  67.                 /* Wait until the request is complete.*/
  68.                 rQueue.waitUntilComplete();
  69.         }
  70.        
  71.         // ===========================================================
  72.         // Worker Class
  73.         // ===========================================================
  74.        
  75.         private class MyEventHandler implements EventHandler {
  76.                 private static final int RANDOM_ID = 0x1337;
  77.  
  78.                 /** Will hold the data returned by the URLCall. */
  79.                 ByteArrayBuffer baf = new ByteArrayBuffer(20);
  80.                
  81.                 /** Needed, as we want to show the results as Notifications. */
  82.                 private Activity myActivity;
  83.  
  84.                 MyEventHandler(Activity activity) {
  85.                         this.myActivity = activity;  }
  86.  
  87.                 public void data(byte[] bytes, int len) {
  88.                         baf.append(bytes, 0, len);  }
  89.  
  90.                 public void endData() {
  91.                         String text = new String(baf.toByteArray());
  92.                         myShowNotificationAndLog("Data loaded: n" + text);  }
  93.  
  94.                 public void status(int arg0, int arg1, int arg2, String s) {
  95.                         myShowNotificationAndLog("status [" + s + "]");  }
  96.  
  97.                 public void error(int i, String s) {
  98.                         this.myShowNotificationAndLog("error [" + s + "]");  }
  99.  
  100.                 public void handleSslErrorRequest(int arg0, String arg1, SslCertificate arg2) { }
  101.                 public void headers(Iterator arg0) { }
  102.                 public void headers(Headers arg0) { }
  103.  
  104.                 private void myShowNotificationAndLog(String msg) {
  105.                         /* Print msg to LogCat and show Notification. */
  106.                         Log.d(DEBUG_TAG, msg);
  107.                         NotificationManager nm = (NotificationManager) this.myActivity
  108.                                         .getSystemService(Activity.NOTIFICATION_SERVICE);
  109.                         nm.notifyWithText(RANDOM_ID, msg, NotificationManager.LENGTH_LONG, null);
  110.                 }
  111.         }
  112. }
Parsed in 0.051 seconds, using GeSHi 1.0.8.4


Regards,
plusminus
Last edited by plusminus on Fri Mar 28, 2008 4:47 pm, edited 2 times in total.
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Top

Postby cabernet1976 » Fri Jan 11, 2008 3:13 pm

Hi plusminus,
I haven't use android.net.http.RequestQueue (I cannot find it in android official document) to do POST, I have two questions about your implement:
1. Is RequestQueue better then HttpURLConnection?
2. or could you make explaina about RequestQueue? For example, when there are large count of packages need to be POSTed, whether the RequestQueue will have better perfermance?

Please tell me if I haven't clarified them. The following is my code to do POST:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.  
  2.     private InputStream doPost(String urlString, String content) throws IOException {
  3.  
  4.         URL url = new URL(urlString);
  5.  
  6.         HttpURLConnection con = (HttpURLConnection) url.openConnection();
  7.  
  8.         InputStream in = null;
  9.  
  10.         OutputStream out;
  11.  
  12.         byte[] buff;
  13.  
  14.         con.setRequestMethod("POST");
  15.  
  16.         con.setDoOutput(true);
  17.  
  18.         con.setDoInput(true);
  19.  
  20.         con.connect();
  21.  
  22.         out = con.getOutputStream();
  23.  
  24.         buff = content.getBytes("UTF8");
  25.  
  26.         out.write(buff);
  27.  
  28.         out.flush();
  29.  
  30.         out.close();
  31.  
  32.         in = con.getInputStream();
  33.  
  34.  
  35.  
  36.         return in;
  37.  
  38.     }
  39.  
  40.  
Parsed in 0.038 seconds, using GeSHi 1.0.8.4
Upload2Flickr's blog: http://upload2flickr.blogspot.com
cabernet1976
Senior Developer
Senior Developer
 
Posts: 154
Joined: Fri Nov 16, 2007 2:34 am
Location: China

Postby cabernet1976 » Fri Jan 11, 2008 3:33 pm

Hi plusminus,

Continue to talk about RequestQueue, how do you think about this thread? :arrow: http://www.anddev.org/upload_files_to_w ... -t443.html :?:
RequestQueue should be able to do upload file to web server, right?

If the program need to upload so many files one by one in a period, sure you are clear this scenario, a queue should be fine, but I have no idea to use RequestQueue to implement it.

BTW. happy week end :!:
Upload2Flickr's blog: http://upload2flickr.blogspot.com
cabernet1976
Senior Developer
Senior Developer
 
Posts: 154
Joined: Fri Nov 16, 2007 2:34 am
Location: China

Postby cabernet1976 » Fri Jan 11, 2008 4:57 pm

Hi plusminus,

Well, after minutes, I get the different of those two sloutioins, yours is a event-drive asynchronous mode implement, and another one is a synchronous implement.

* event-drive mode make it able to implement the program with only one thread even the HTTP connect cast long time.

* synchronous mode is easy to write the code, but the main thread will timeout if HTTP connection cast too long time, unless add a new thread to do HTTP.

Please correct me.
Thanks.
Upload2Flickr's blog: http://upload2flickr.blogspot.com
cabernet1976
Senior Developer
Senior Developer
 
Posts: 154
Joined: Fri Nov 16, 2007 2:34 am
Location: China

Postby plusminus » Fri Jan 11, 2008 5:24 pm

Hello cabernet,

exactly, your code will be blocking probably when reading from the InputStream. Mine got a few lines more, but is probably more handy to implement, for example because you get notified of Errors and no need to create a thread on your own (internally there will be created one for you).

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby cabernet1976 » Sat Jan 12, 2008 1:57 am

Thanks for your reply, plusminus.
I got it.
Upload2Flickr's blog: http://upload2flickr.blogspot.com
cabernet1976
Senior Developer
Senior Developer
 
Posts: 154
Joined: Fri Nov 16, 2007 2:34 am
Location: China

Top

Re: Doing HTTP Post with Android

Postby tangoman » Sun Jan 13, 2008 8:08 pm

Hi PlusMinus!
Congrats about your tutorial, it's really clear!
How ever I got a problem trying it.

I just changed it your URL, for:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. rQueue.queueRequest("http://localhost:8080/postresponse.htm" "POST",
  2.  
  3.                             headers, myEvH, baos, POSTbytes.length,false);
Parsed in 0.036 seconds, using GeSHi 1.0.8.4


and I exposed a controller in Java that attends that URL, and prints the data that came in mydata (I tried it from a browser and works right)

The error I'm a having is a " Error, Connection Refused"
Any Idea?

one more question!, lets say I got to pass another variable. Is as easy as concat the that new var to the firstone? (without &)

Thanks! in advance!

Tangoman.
tangoman
Freshman
Freshman
 
Posts: 7
Joined: Sun Jan 13, 2008 7:54 pm

Postby plusminus » Sun Jan 13, 2008 8:51 pm

Hello tangoman,

Remember that the emulator you are running is a fully separated system :!:
So "localhost"/"127.0.0.1" is the Emulator itself :!:

You access the WebServer which is probably running on your Desktop-PC via an IP like "192.168.X.X" or "10.10.X.X". Determine your actual IP with "ipconfig" / "ifconfig" on CmdLine / Shell.

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby tangoman » Sun Jan 13, 2008 9:17 pm

:)
Thanks a lot!, PlusMinus!.

Excelent tut!!!

later!

Tangoman
tangoman
Freshman
Freshman
 
Posts: 7
Joined: Sun Jan 13, 2008 7:54 pm

Postby Nanodeath » Tue Jan 15, 2008 7:07 am

Hi all. Very nice work plusminus -- I thought I'd pack the code into a tidy class and add a bit of functionality. It now supports GET as well as POST.

Class:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. import java.io.ByteArrayInputStream;
  2.  
  3. import java.io.UnsupportedEncodingException;
  4.  
  5. import java.net.URLEncoder;
  6.  
  7. import java.util.HashMap;
  8.  
  9. import java.util.Iterator;
  10.  
  11. import java.util.Map;
  12.  
  13. import java.util.Set;
  14.  
  15.  
  16.  
  17. import org.apache.http.util.ByteArrayBuffer;
  18.  
  19.  
  20.  
  21. import android.content.Context;
  22.  
  23. import android.net.http.EventHandler;
  24.  
  25. import android.net.http.Headers;
  26.  
  27. import android.net.http.RequestQueue;
  28.  
  29. import android.net.http.SslCertificate;
  30.  
  31. import android.util.Log;
  32.  
  33.  
  34.  
  35. public class HTTP_Request {
  36.  
  37.  
  38.  
  39.         // ===========================================================
  40.  
  41.         // Fields
  42.  
  43.         // ===========================================================
  44.  
  45.  
  46.  
  47.         private Context context;
  48.  
  49.         private String url;
  50.  
  51.         private String variables;
  52.  
  53.         private Method method;
  54.  
  55.        
  56.  
  57.         public enum Method {
  58.  
  59.                 POST,
  60.  
  61.                 GET
  62.  
  63.         }
  64.  
  65.  
  66.  
  67.         // ===========================================================
  68.  
  69.         // 'Constructors'
  70.  
  71.         // ===========================================================
  72.  
  73.  
  74.  
  75.         // Constructor for requests without variables
  76.  
  77.         public HTTP_Request(Context c, String url, Method method){
  78.  
  79.                 this(c, url, method, null);
  80.  
  81.         }
  82.  
  83.        
  84.  
  85.         // Constructor for requests with variables
  86.  
  87.         public HTTP_Request(Context c, String url, Method method, Map<String,String> variables) {
  88.  
  89.                 this.context = c;
  90.  
  91.                 this.url = url;
  92.  
  93.                 this.variables = "";
  94.  
  95.                 this.method = method;
  96.  
  97.                
  98.  
  99.                 /* Prepare the variables we are going to send. */
  100.  
  101.                 if(variables != null){
  102.  
  103.                         try {
  104.  
  105.                                 StringBuilder b = new StringBuilder();
  106.  
  107.                                 Set keys = variables.keySet();
  108.  
  109.                                 for(Iterator i = keys.iterator(); i.hasNext();){
  110.  
  111.                                         String key = (String)i.next();
  112.  
  113.                                         b.append(key);
  114.  
  115.                                         b.append("=");
  116.  
  117.                                         b.append(URLEncoder.encode(variables.get(key), "UTF-8"));
  118.  
  119.                                         if(i.hasNext()){
  120.  
  121.                                                 b.append("&");
  122.  
  123.                                         }
  124.  
  125.                                 }
  126.  
  127.                                 this.variables = b.toString();
  128.  
  129.                         } catch (UnsupportedEncodingException e) {
  130.  
  131.                                 Log.e("HTTP_Request", "Unsupported Encoding Exception");
  132.  
  133.                                 return;
  134.  
  135.                         }
  136.  
  137.                 }
  138.  
  139.         }
  140.  
  141.  
  142.  
  143.         private PostHandler handler;
  144.  
  145.  
  146.  
  147.         public void setHandler(PostHandler h){
  148.  
  149.                 handler = h;
  150.  
  151.         }
  152.  
  153.  
  154.  
  155.         public void go(){
  156.  
  157.                 /* Create a new EventHandler defined above, to handle what gets returned. */
  158.  
  159.                 MyEventHandler myEvH = new MyEventHandler(handler);
  160.  
  161.  
  162.  
  163.                 /* Create a new HTTP-RequestQueue. */
  164.  
  165.                 android.net.http.RequestQueue rQueue = new RequestQueue(context);        
  166.  
  167.  
  168.  
  169.                 /* Create a header-hashmap */
  170.  
  171.                 Map<String, String> headers = new HashMap<String, String>();
  172.  
  173.                 /* and put the Default-Encoding for html-forms to it. */
  174.  
  175.                 headers.put("Content-Type", "application/x-www-form-urlencoded");
  176.  
  177.  
  178.  
  179.                 if(method == Method.GET){
  180.  
  181.                         // Perform the request with GET
  182.  
  183.                         if(!variables.equals("")){
  184.  
  185.                                 url = url + "?" + variables;
  186.  
  187.                         }
  188.  
  189.                         rQueue.queueRequest(url, "GET", headers, myEvH, null, 0, false);
  190.  
  191.                 } else if(method == Method.POST){
  192.  
  193.                         /* And put the encoded bytes into an BAIS,
  194.  
  195.                          * where a function later can read bytes from. */
  196.  
  197.                         byte[] POSTbytes = variables.getBytes();
  198.  
  199.                         ByteArrayInputStream baos = new ByteArrayInputStream(POSTbytes);
  200.  
  201.                         rQueue.queueRequest(url, "POST", headers, myEvH, baos, POSTbytes.length, false);                       
  202.  
  203.                 }
  204.  
  205.                
  206.  
  207.                 /* Wait until the request is complete.*/
  208.  
  209.                 rQueue.waitUntilComplete();
  210.  
  211.         }
  212.  
  213.  
  214.  
  215.         // ===========================================================
  216.  
  217.         // Worker Class
  218.  
  219.         // ===========================================================
  220.  
  221.  
  222.  
  223.         private class MyEventHandler implements EventHandler {
  224.  
  225.                 private PostHandler handler;
  226.  
  227.  
  228.  
  229.                 /** Will hold the data returned by the URLCall. */
  230.  
  231.                 ByteArrayBuffer baf = new ByteArrayBuffer(20);
  232.  
  233.  
  234.  
  235.                 MyEventHandler(PostHandler callback) {
  236.  
  237.                         this.handler = callback;
  238.  
  239.                 }
  240.  
  241.  
  242.  
  243.                 public void data(byte[] bytes, int len) {
  244.  
  245.                         baf.append(bytes, 0, len);
  246.  
  247.                 }
  248.  
  249.  
  250.  
  251.                 public void endData() {
  252.  
  253.                         handler.run(new String(baf.toByteArray()));
  254.  
  255.                 }
  256.  
  257.  
  258.  
  259.                 public void status(int arg0, int arg1, int arg2, String s) {
  260.  
  261.                         // Status can be OK, Not Found, others...
  262.  
  263.                         handler.status(s);
  264.  
  265.                 }
  266.  
  267.  
  268.  
  269.                 public void error(int i, String s) {
  270.  
  271.                         handler.error(s);
  272.  
  273.                 }
  274.  
  275.  
  276.  
  277.                 public void handleSslErrorRequest(int arg0, String arg1, SslCertificate arg2) { }
  278.  
  279.                 public void headers(Iterator arg0) { }
  280.  
  281.                 public void headers(Headers arg0) { }
  282.  
  283.         }
  284.  
  285.  
  286.  
  287.         public static abstract class PostHandler {
  288.  
  289.                 abstract void run(String response);
  290.  
  291.                 void status(String status) {}
  292.  
  293.                 void error(String error) {}
  294.  
  295.         }
  296.  
  297. }
Parsed in 0.055 seconds, using GeSHi 1.0.8.4


Also, here is some sample usage:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. Map<String,String> vars = new HashMap<String,String>();
  2.  
  3.                         vars.put("test", "value");
  4.  
  5.                         vars.put("othertest", "valuedos");
  6.  
  7.                        
  8.  
  9.                         HTTP_Request request = new HTTP_Request(NutriScan.this, "http://www.samplewebsite.com/test.php", HTTP_Request.Method.GET, vars);
  10.  
  11.                         request.setHandler(new PostHandler(){
  12.  
  13.                                 void run(String response) {
  14.  
  15.                                         Log.d(TAG, "RESPONSE: " + response);
  16.  
  17.                                 }
  18.  
  19.  
  20.  
  21.                                 @Override
  22.  
  23.                                 void error(String error) {
  24.  
  25.                                         Log.e(TAG, "ERROR: " + error);
  26.  
  27.                                 }
  28.  
  29.  
  30.  
  31.                                 @Override
  32.  
  33.                                 void status(String status) {
  34.  
  35.                                         Log.i(TAG, "STATUS:" + status);
  36.  
  37.                                 }
  38.  
  39.                         });
  40.  
  41.                         request.go();
Parsed in 0.039 seconds, using GeSHi 1.0.8.4
Nanodeath
Junior Developer
Junior Developer
 
Posts: 15
Joined: Tue Jan 15, 2008 6:56 am

Postby tangoman » Tue Jan 15, 2008 2:01 pm

Hi Nano, nice Job!

I got a few questions that probably any could answer.
In the line:

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. HTTP_Request request = new HTTP_Request(NutriScan.this, "http://www.samplewebsite.com/test.php", HTTP_Request.Method.GET, vars);
Parsed in 0.036 seconds, using GeSHi 1.0.8.4


What NutriScan.this does mean? a Context? And that's when my second question comes:
How would you do to get a Context, if your not in a Activity class when you inherite from Context and just pass this. What alternatives does we have to get a context?
I think that is a really common doubt dealing with context, so if any could help to clear it would really nice!.

Thanks a lot!!

Tangoman.
tangoman
Freshman
Freshman
 
Posts: 7
Joined: Sun Jan 13, 2008 7:54 pm

Postby Nanodeath » Tue Jan 15, 2008 6:02 pm

NutriScan is the name of the project I happened to be testing this application from. That line gets the context -- I can't simply say this because it happens to be in a OnClick listener and so simply saying this would actually refer to the click handler (I think). So somehow, if you're calling the function from an activity, you have to say either this or thatActivity.this, depending on the circumstances/whatever works. I don't fully understand it myself, but hopefully that's enough.

I'm pretty sure that you can't do this without the context. If Activity A calls Class B, and you're trying to use this function in Class B, then you're going to have to force Activity A to pass its context to Class B for use with functions like this. Or possibly you could still say A.this? I'm not really sure.

Hope some of this helps you a bit -- this is my learning project as well.
Nanodeath
Junior Developer
Junior Developer
 
Posts: 15
Joined: Tue Jan 15, 2008 6:56 am

Postby plusminus » Wed Jan 16, 2008 12:28 am

Hello Nanodeath,

big thx for your submission. This will be really useful for others!

Nanodeath wrote:NutriScan is the name of the project I happened to be testing this application from. That line gets the context -- I can't simply say this because it happens to be in a OnClick listener and so simply saying this would actually refer to the click handler (I think). So somehow, if you're calling the function from an activity, you have to say either this or thatActivity.this, depending on the circumstances/whatever works. I don't fully understand it myself, but hopefully that's enough.

Yes, the example code you provided was probably contained in a private/anonymous class (like an anonymous OnClickListener). So using this within such an OnClickListener if you want to refer to the OnClickListener we are typing the code in. So we explicitly have to say that we want to refer to the 'surrounding' Activity (Note: Activity extends Context!).

Nanodeath wrote:I'm pretty sure that you can't do this without the context.

Yes, because the constructor of RequestQueue wants to be fed with the context. :)
Nanodeath wrote:If Activity A calls Class B, and you're trying to use this function in Class B, then you're going to have to force Activity A to pass its context to Class B for use with functions like this. Or possibly you could still say A.this? I'm not really sure.

Hope some of this helps you a bit -- this is my learning project as well.

No the context is needed nowhere in this example except in the constructor of RequestQueue.

@tangoman
What alternatives does we have to get a context?

Actually none :)

Regards,
plusminus
Image
Image | Android Development Community / Tutorials
User avatar
plusminus
Site Admin
Site Admin
 
Posts: 2688
Joined: Wed Nov 14, 2007 8:37 pm
Location: Schriesheim, Germany

Postby Nanodeath » Wed Jan 16, 2008 1:05 am

Thanks for confirming some of that. Also, with respect to the Context stuff, I was referring to a case not demonstrated by my sample code, if that makes any difference.
Nanodeath
Junior Developer
Junior Developer
 
Posts: 15
Joined: Tue Jan 15, 2008 6:56 am

Postby tangoman » Wed Jan 16, 2008 12:11 pm

Thanks!!!! Both!, Nanodeath and PlusMinus for the answers!

Tangoman
tangoman
Freshman
Freshman
 
Posts: 7
Joined: Sun Jan 13, 2008 7:54 pm

Top
Next

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 1 guest