AsyncTask working: launching a new Task and storing the cookie
authorgumartinm <gu.martinm@gmail.com>
Wed, 14 Dec 2011 00:01:48 +0000 (01:01 +0100)
committergumartinm <gu.martinm@gmail.com>
Wed, 14 Dec 2011 00:01:48 +0000 (01:01 +0100)
Test2: DefaultHttpClient, for the new Android version it is a must to chage
the default policy about threads using sockets (the UI must be as fast as possible)

14 files changed:
Android/Testing/Test1/res/layout/main.xml
Android/Testing/Test1/src/de/android/test1/MobieAdHttpAuthClient.java
Android/Testing/Test1/src/de/android/test1/NextActivity.java
Android/Testing/Test1/src/de/android/test1/Test1Activity.java
Android/Testing/Test2/AndroidManifest.xml [new file with mode: 0644]
Android/Testing/Test2/gen/de/android/test2/R.java [new file with mode: 0644]
Android/Testing/Test2/proguard.cfg [new file with mode: 0644]
Android/Testing/Test2/project.properties [new file with mode: 0644]
Android/Testing/Test2/res/drawable-hdpi/ic_launcher.png [new file with mode: 0644]
Android/Testing/Test2/res/drawable-ldpi/ic_launcher.png [new file with mode: 0644]
Android/Testing/Test2/res/drawable-mdpi/ic_launcher.png [new file with mode: 0644]
Android/Testing/Test2/res/layout/main.xml [new file with mode: 0644]
Android/Testing/Test2/res/values/strings.xml [new file with mode: 0644]
Android/Testing/Test2/src/de/android/test2/Test2Activity.java [new file with mode: 0644]

index 15264ad..cf49719 100644 (file)
                android:id="@+id/username"
                android:singleLine="true"
            android:layout_width="fill_parent"
-           android:layout_height="wrap_content" android:text="@string/username"/>
-       <TextView
-           android:layout_width="fill_parent"
-           android:layout_height="wrap_content"
-           android:text="Password:"
-           />
+           android:layout_height="wrap_content" 
+           android:hint="@string/username"/>
+       
        <EditText
                android:id="@+id/password"
                android:password="true"
                android:singleLine="true"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
-               android:text="@string/password"/>
+               android:hint="@string/password"/>
        <FrameLayout 
                android:layout_width="match_parent" 
                android:id="@+id/frameLayout2" 
index ebcdb6f..50bbb55 100644 (file)
@@ -6,6 +6,7 @@ import java.net.URISyntaxException;
 import java.net.URL;
 import java.util.ArrayList;
 import java.util.List;
+
 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.HttpStatus;
@@ -14,20 +15,27 @@ import org.apache.http.client.ClientProtocolException;
 import org.apache.http.client.entity.UrlEncodedFormEntity;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.message.BasicNameValuePair;
+
+import android.content.Context;
+import android.content.Intent;
 import android.net.http.AndroidHttpClient;
 import android.os.AsyncTask;
 import android.util.Log;
+import android.webkit.CookieManager;
+import android.webkit.CookieSyncManager;
 
 public class MobieAdHttpAuthClient extends AsyncTask<URL, Integer, HttpResponse> {
        private static final String TAG = "MobieAdHttpAuthClient";
        private AndroidHttpClient httpClient;
        private final String username;
        private final String password;
+       private final Context context;
        
-       public MobieAdHttpAuthClient(final String username, final String password)
+       public MobieAdHttpAuthClient(final String username, final String password, Context context)
        {
                this.username = username;
                this.password = password;
+               this.context = context;
        }
        
        @Override
@@ -36,7 +44,8 @@ public class MobieAdHttpAuthClient extends AsyncTask<URL, Integer, HttpResponse>
                final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                final HttpPost httpPost = new HttpPost();
                HttpResponse httpResponse = null;
-               HttpEntity httpEntity = null;      
+               HttpEntity httpEntity = null;
+
         
         //TODO: RESTful Web Service must use JSON instead of signin array :(
         nameValuePairs.add(new BasicNameValuePair("signin[username]", this.username));
@@ -72,21 +81,28 @@ public class MobieAdHttpAuthClient extends AsyncTask<URL, Integer, HttpResponse>
        protected void onPostExecute(final HttpResponse result)
        {
                this.httpClient.close();
-               //Never should be null but this check should be not harmful
+               //It should not be null anyway this check is not harmful
                if (result != null)
                {
-                       if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
-                       {
-                               //OK GO TO THE NEXT ACTIVITY
+                       switch (result.getStatusLine().getStatusCode()) {
+                               case HttpStatus.SC_OK:
+                                       String cookie = result.getLastHeader("Set-Cookie").getValue();
+                                       CookieManager.getInstance().setCookie("192.168.1.34/userfront.php",cookie);
+                                       CookieSyncManager.getInstance().sync();
+                                       //OK GO TO THE NEXT ACTIVITY
+                                       Intent i = new Intent(this.context, NextActivity.class);
+                               this.context.startActivity(i);
+                                       break;
+                               case HttpStatus.SC_UNAUTHORIZED:
+                                       //ERROR IN USERNAME OR PASSWORD
+                                       break;
+                               case HttpStatus.SC_BAD_REQUEST:
+                                       //WHAT THE HECK ARE YOU DOING?
+                                       break;
+                               default:
+                                       Log.e(TAG, "Error while retrieving the HTTP status line.");
+                                       break;
                        }
-                       if (result.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED)
-                       {
-                               //ERROR IN USERNAME OR PASSWORD
-                       }
-                       if (result.getStatusLine().getStatusCode() == HttpStatus.SC_BAD_REQUEST)
-                       {
-                               //WHAT THE HECK ARE YOU DOING?
-                       }
-               }
+               }       
        }
 }
index 2242fe3..5e769db 100644 (file)
@@ -2,12 +2,16 @@ package de.android.test1;
 
 import android.app.Activity;
 import android.os.Bundle;
+import android.webkit.CookieManager;
+import android.webkit.CookieSyncManager;
 
 public class NextActivity extends Activity {
         /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
+        CookieSyncManager.createInstance(this);
+        String myCookie = CookieManager.getInstance().getCookie("192.168.1.34/userfront.php");
         setContentView(R.layout.main2);
     }
 }
index 4533d5f..56a2dde 100644 (file)
@@ -1,11 +1,29 @@
 package de.android.test1;
 
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
 import java.net.MalformedURLException;
+import java.net.URISyntaxException;
 import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpStatus;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.message.BasicNameValuePair;
 import android.app.Activity;
 import android.content.Intent;
+import android.net.http.AndroidHttpClient;
+import android.os.AsyncTask;
 import android.os.Bundle;
+import android.util.Log;
 import android.view.View;
+import android.webkit.CookieManager;
+import android.webkit.CookieSyncManager;
 import android.widget.EditText;
 
 public class Test1Activity extends Activity {
@@ -14,7 +32,8 @@ public class Test1Activity extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
-        super.onCreate(savedInstanceState);       
+        super.onCreate(savedInstanceState);
+        CookieSyncManager.createInstance(this);
         setContentView(R.layout.main);
     }
     
@@ -36,10 +55,7 @@ public class Test1Activity extends Activity {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
-               new MobieAdHttpAuthClient(username.getText().toString(), password.getText().toString()).execute(url);
-
-       //Intent i = new Intent(Test1Activity.this, NextActivity.class);
-       //this.startActivity(i);
+               new MobieAdHttpAuthClient(username.getText().toString(), password.getText().toString(), this).execute(url);
     }
     
     public void onClickCancel(View v) {
diff --git a/Android/Testing/Test2/AndroidManifest.xml b/Android/Testing/Test2/AndroidManifest.xml
new file mode 100644 (file)
index 0000000..57577ad
--- /dev/null
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="de.android.test2"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <uses-sdk android:minSdkVersion="14" />
+    <uses-permission android:name="android.permission.INTERNET"/>
+
+    <application
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name" >
+        <activity
+            android:label="@string/app_name"
+            android:name=".Test2Activity" 
+            android:screenOrientation="portrait" 
+            android:configChanges="touchscreen|keyboard"
+            android:theme="@android:style/Theme.Black" 
+            android:permission="android.permission.INTERNET" 
+            android:launchMode="standard">
+            <intent-filter >
+                <action android:name="android.intent.action.MAIN" />
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+        
+        <activity 
+                       android:label="@string/app_name"
+                       android:name=".NextActivity" >
+               </activity>
+               
+    </application>
+
+</manifest>
\ No newline at end of file
diff --git a/Android/Testing/Test2/gen/de/android/test2/R.java b/Android/Testing/Test2/gen/de/android/test2/R.java
new file mode 100644 (file)
index 0000000..37ca302
--- /dev/null
@@ -0,0 +1,36 @@
+/* AUTO-GENERATED FILE.  DO NOT MODIFY.
+ *
+ * This class was automatically generated by the
+ * aapt tool from the resource data it found.  It
+ * should not be modified by hand.
+ */
+
+package de.android.test2;
+
+public final class R {
+    public static final class attr {
+    }
+    public static final class drawable {
+        public static final int ic_launcher=0x7f020000;
+    }
+    public static final class id {
+        public static final int cancel_button=0x7f050005;
+        public static final int frameLayout1=0x7f050000;
+        public static final int frameLayout2=0x7f050003;
+        public static final int login_button=0x7f050004;
+        public static final int password=0x7f050002;
+        public static final int username=0x7f050001;
+    }
+    public static final class layout {
+        public static final int main=0x7f030000;
+    }
+    public static final class string {
+        public static final int app_name=0x7f040001;
+        public static final int button_cancel=0x7f040006;
+        public static final int button_login=0x7f040004;
+        public static final int button_ok=0x7f040005;
+        public static final int hello=0x7f040000;
+        public static final int password=0x7f040003;
+        public static final int username=0x7f040002;
+    }
+}
diff --git a/Android/Testing/Test2/proguard.cfg b/Android/Testing/Test2/proguard.cfg
new file mode 100644 (file)
index 0000000..b1cdf17
--- /dev/null
@@ -0,0 +1,40 @@
+-optimizationpasses 5
+-dontusemixedcaseclassnames
+-dontskipnonpubliclibraryclasses
+-dontpreverify
+-verbose
+-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
+
+-keep public class * extends android.app.Activity
+-keep public class * extends android.app.Application
+-keep public class * extends android.app.Service
+-keep public class * extends android.content.BroadcastReceiver
+-keep public class * extends android.content.ContentProvider
+-keep public class * extends android.app.backup.BackupAgentHelper
+-keep public class * extends android.preference.Preference
+-keep public class com.android.vending.licensing.ILicensingService
+
+-keepclasseswithmembernames class * {
+    native <methods>;
+}
+
+-keepclasseswithmembers class * {
+    public <init>(android.content.Context, android.util.AttributeSet);
+}
+
+-keepclasseswithmembers class * {
+    public <init>(android.content.Context, android.util.AttributeSet, int);
+}
+
+-keepclassmembers class * extends android.app.Activity {
+   public void *(android.view.View);
+}
+
+-keepclassmembers enum * {
+    public static **[] values();
+    public static ** valueOf(java.lang.String);
+}
+
+-keep class * implements android.os.Parcelable {
+  public static final android.os.Parcelable$Creator *;
+}
diff --git a/Android/Testing/Test2/project.properties b/Android/Testing/Test2/project.properties
new file mode 100644 (file)
index 0000000..730e911
--- /dev/null
@@ -0,0 +1,11 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system use,
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+
+# Project target.
+target=android-14
diff --git a/Android/Testing/Test2/res/drawable-hdpi/ic_launcher.png b/Android/Testing/Test2/res/drawable-hdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..8074c4c
Binary files /dev/null and b/Android/Testing/Test2/res/drawable-hdpi/ic_launcher.png differ
diff --git a/Android/Testing/Test2/res/drawable-ldpi/ic_launcher.png b/Android/Testing/Test2/res/drawable-ldpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..1095584
Binary files /dev/null and b/Android/Testing/Test2/res/drawable-ldpi/ic_launcher.png differ
diff --git a/Android/Testing/Test2/res/drawable-mdpi/ic_launcher.png b/Android/Testing/Test2/res/drawable-mdpi/ic_launcher.png
new file mode 100644 (file)
index 0000000..a07c69f
Binary files /dev/null and b/Android/Testing/Test2/res/drawable-mdpi/ic_launcher.png differ
diff --git a/Android/Testing/Test2/res/layout/main.xml b/Android/Testing/Test2/res/layout/main.xml
new file mode 100644 (file)
index 0000000..89a734a
--- /dev/null
@@ -0,0 +1,49 @@
+<?xml version="1.0" encoding="utf-8"?>
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:gravity="right"
+    android:layout_width="match_parent" 
+    android:layout_height="match_parent" 
+    android:orientation="vertical" 
+    android:weightSum="1">
+    
+    <FrameLayout 
+       android:id="@+id/frameLayout1" 
+       android:layout_width="match_parent" android:layout_height="70dp">
+    </FrameLayout>
+           
+       <EditText
+               android:id="@+id/username"
+               android:singleLine="true"
+           android:layout_width="fill_parent"
+           android:layout_height="wrap_content" 
+           android:hint="@string/username"/>
+       
+       <EditText
+               android:id="@+id/password"
+               android:password="true"
+               android:singleLine="true"
+           android:layout_width="fill_parent"
+           android:layout_height="wrap_content"
+               android:hint="@string/password"/>
+       <FrameLayout 
+               android:layout_width="match_parent" 
+               android:id="@+id/frameLayout2" 
+               android:layout_height="30dp">
+       </FrameLayout>
+       <Button
+               android:id="@+id/login_button"
+               android:onClick="onClickLogin"
+           android:layout_height="wrap_content" 
+           android:text="@string/button_login" 
+           android:layout_width="match_parent" 
+           android:layout_gravity="center"/>
+       <Button
+               android:id="@+id/cancel_button"
+               android:onClick="onClickCancel"
+               android:gravity="right" 
+           android:layout_height="wrap_content" 
+           android:layout_width="wrap_content" 
+           android:layout_gravity="right" 
+           android:text="@string/button_cancel"/>
+       
+</LinearLayout>
\ No newline at end of file
diff --git a/Android/Testing/Test2/res/values/strings.xml b/Android/Testing/Test2/res/values/strings.xml
new file mode 100644 (file)
index 0000000..8c6136f
--- /dev/null
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+    <string name="hello">Hello World, Test2Activity!</string>
+    <string name="app_name">Test2</string>
+    <string name="username">Username</string>
+    <string name="password">Password</string>
+    <string name="button_login">Log In</string>
+    <string name="button_ok">OK</string>
+    <string name="button_cancel">Cancel</string>
+</resources>
\ No newline at end of file
diff --git a/Android/Testing/Test2/src/de/android/test2/Test2Activity.java b/Android/Testing/Test2/src/de/android/test2/Test2Activity.java
new file mode 100644 (file)
index 0000000..72c89a0
--- /dev/null
@@ -0,0 +1,96 @@
+package de.android.test2;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.List;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpStatus;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.message.BasicNameValuePair;
+import android.app.Activity;
+import android.os.Bundle;
+import android.os.StrictMode;
+import android.util.Log;
+import android.view.View;
+import android.webkit.CookieManager;
+import android.webkit.CookieSyncManager;
+import android.widget.EditText;
+
+public class Test2Activity extends Activity {
+       private static final String TAG = "Test2Activity";
+    /** Called when the activity is first created. */
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        CookieSyncManager.createInstance(this);
+        StrictMode.ThreadPolicy currentPolicy = StrictMode.getThreadPolicy();
+        StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
+        setContentView(R.layout.main);
+    }
+    
+    public void onClickLogin(View v) {
+       final String URLAuth = "http://192.168.1.34/userfront.php/api/login/auth.json";
+       final EditText password = (EditText) findViewById(R.id.password);
+       final EditText username = (EditText) findViewById(R.id.username);
+
+               HttpClient httpClient = new DefaultHttpClient();
+               HttpPost httpPost = new HttpPost(URLAuth);
+               HttpEntity httpEntity = null;
+               HttpResponse httpResponse = null;
+               final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
+               
+               //TODO: RESTful Web Service must use JSON instead of signin array :(
+        nameValuePairs.add(new BasicNameValuePair("signin[username]", username.getText().toString()));
+        nameValuePairs.add(new BasicNameValuePair("signin[password]", password.getText().toString()));
+        try {
+                       httpEntity = new UrlEncodedFormEntity(nameValuePairs);
+               } catch (UnsupportedEncodingException e) {
+                       Log.e(TAG, "Error while encoding POST parameters." + e);
+               }
+        httpPost.setEntity(httpEntity);
+        httpPost.setHeader("User-Agent", "MobieAds/1.0");
+        
+        try {
+                       httpResponse = httpClient.execute(httpPost);
+               } catch (ClientProtocolException e1) {
+                       Log.e(TAG, "Error while executing HTTP client connection.");
+               } catch (IOException e1) {
+                       Log.e(TAG, "Error while executing HTTP client connection.");
+               }
+        
+        if (httpResponse != null)
+               {
+                       switch (httpResponse.getStatusLine().getStatusCode()) {
+                               case HttpStatus.SC_OK:
+                                       String cookie = httpResponse.getLastHeader("Set-Cookie").getValue();
+                                       CookieManager.getInstance().setCookie("192.168.1.34/userfront.php",cookie);
+                                       CookieSyncManager.getInstance().sync();
+                                       //OK GO TO THE NEXT ACTIVITY
+                                       break;
+                               case HttpStatus.SC_UNAUTHORIZED:
+                                       //ERROR IN USERNAME OR PASSWORD
+                                       break;
+                               case HttpStatus.SC_BAD_REQUEST:
+                                       //WHAT THE HECK ARE YOU DOING?
+                                       break;
+                               default:
+                                       Log.e(TAG, "Error while retrieving the HTTP status line.");
+                                       break;
+                       }
+               }
+        String myCookie = CookieManager.getInstance().getCookie("192.168.1.34/userfront.php");
+               Log.e("hola", "Error while retrieving the HTTP status line." + myCookie);
+        
+    }
+    
+    public void onClickCancel(View v) {
+       finish();
+    }
+}
\ No newline at end of file