{"id":6212,"date":"2014-04-13T23:07:30","date_gmt":"2014-04-13T23:07:30","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2014\/04\/13\/android-httpclient-asynctask-collection-of-common-programming-errors\/"},"modified":"2014-04-13T23:07:30","modified_gmt":"2014-04-13T23:07:30","slug":"android-httpclient-asynctask-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2014\/04\/13\/android-httpclient-asynctask-collection-of-common-programming-errors\/","title":{"rendered":"Android HttpClient Asynctask-Collection of common programming errors"},"content":{"rendered":"<p>I have been stuck on this problem for a day or two now, so i decided to see if anyone out there could help me.<\/p>\n<p>The current goal i have, is to make a HttpPost that connects to, and executes a script that i have on my Wamp server. I have implemented a class that extends AsyncTask, and includes the 3 necessary methods, that are required in order for it to work effectively.<\/p>\n<p>I will first show you the code that i have used to put the variables into a Json Object, followed by the <code>JSONParser<\/code> class, that initializes the <code>HttpPost<\/code> and then executes it.<br \/>\nAfterwards i will tell you all about the log errors and the narrowing down of the problem; you all problem know what the problem may be already, and if you don&#8217;t want to read below, briefly, it is caused by the line of code that calls the parser class.<\/p>\n<p>Note: I am using this as a starting point for this type of work, so please understand that it is simple in terms of its passed parameters.<\/p>\n<p>Further Note: I am using Eclipse, and i am testing with the inbuilt Emulator.<\/p>\n<p>METHOD &#8211; CreateNewUser<\/p>\n<pre><code>\/**\n * Background Async Task to Create new user\n *\/\nclass CreateNewUser extends AsyncTask{\n\n\/**\n* Before starting background thread show progress dialog\n*\/\n@Override\nprotected void onPreExecute(){\n    super.onPreExecute();\n    pDialog = new ProgressDialog(AddUserActivity.this);\n    pDialog.setIndeterminate(false);\n    pDialog.setCancelable(true);\n    pDialog.show();\n}\n\n\/*\n* Creating user\n*\/\n@Override\nprotected String doInBackground(String... args){\n\n    String username = inputUsername.getText().toString();\n    String password = inputPassword.getText().toString();\n\n    \/\/ Building parameters\n    List params = new ArrayList();\n    params.add(new BasicNameValuePair(\"username\", username));\n    params.add(new BasicNameValuePair(\"password\", password));\n\n    \/\/ getting JSON object\n    \/\/ Note that create user url accepts POST method\n       JSONObject json = jsonParser.makeHttpRequest(url_create_user, \"POST\",params);               \n\n    \/\/ check log cat for response\n    Log.d(\"Create Response\", json.toString());\n\n        \/\/ check for success tag\n        try {\n            int success = json.getInt(TAG_SUCCESS);\n\n            if (success == 1) {\n                \/\/ successfully created product\n                Intent i = new Intent(getApplicationContext(), MainActivity.class);\n                startActivity(i);\n\n                \/\/ closing this screen\n                finish();\n            } else {\n                \/\/ failed to create product\n            }\n        } catch (JSONException e) {\n            e.printStackTrace();\n        }\n        return null;    \n    }\n\n    \/**\n     * After completing background task Dismiss the progress dialog\n     * **\/\n    @Override\n    protected void onPostExecute(String file_url) {\n        \/\/ dismiss the dialog once done\n        pDialog.dismiss();\n    }\n}\n<\/code><\/pre>\n<p>Next, the JSONParser Class:<\/p>\n<pre><code>public class JSONParser {\n\n    static InputStream is = null;\n    static JSONObject jObj = null;\n    static String json = \"\";\n\n    \/\/ constructor\n    public JSONParser() {\n\n    }\n\n    \/\/ function get JSON from URL\n    \/\/ by making HTTP POST or GET method\n    public JSONObject makeHttpRequest(String url, String method,\n            List params) {\n\n        \/\/ Making HTTP request\n        try {\n\n            \/\/ check for request method\n            if(method == \"POST\"){\n                \/\/ request method is POST\n                \/\/ defaultHttpClient\n                DefaultHttpClient httpClient = new DefaultHttpClient();\n                HttpPost httpPost = new HttpPost(url);\n                httpPost.setEntity(new UrlEncodedFormEntity(params));\n\n                HttpResponse httpResponse = httpClient.execute(httpPost);\n                HttpEntity httpEntity = httpResponse.getEntity();\n                is = httpEntity.getContent();\n\n            }else if(method == \"GET\"){\n                \/\/ request method is GET\n                DefaultHttpClient httpClient = new DefaultHttpClient();\n                String paramString = URLEncodedUtils.format(params, \"utf-8\");\n                url += \"?\" + paramString;\n                HttpGet httpGet = new HttpGet(url);\n\n                HttpResponse httpResponse = httpClient.execute(httpGet);\n                HttpEntity httpEntity = httpResponse.getEntity();\n                is = httpEntity.getContent();\n            }           \n\n        } catch (UnsupportedEncodingException e) {\n            e.printStackTrace();\n        } catch (ClientProtocolException e) {\n            e.printStackTrace();\n        } catch (IOException e) {\n            e.printStackTrace();\n        }\n\n        try {\n            BufferedReader reader = new BufferedReader(new InputStreamReader(\n                    is, \"iso-8859-1\"), 8);\n            StringBuilder sb = new StringBuilder();\n            String line = null;\n            while ((line = reader.readLine()) != null) {\n                sb.append(line + \"\\n\");\n            }\n            is.close();\n            json = sb.toString();\n        } catch (Exception e) {\n            Log.e(\"Buffer Error\", \"Error converting result \" + e.toString());\n        }\n\n        \/\/ try parse the string to a JSON object\n        try {\n            jObj = new JSONObject(json);\n        } catch (JSONException e) {\n            Log.e(\"JSON Parser\", \"Error parsing data \" + e.toString());\n        }\n\n        \/\/ return JSON String\n       return jObj;\n\n    }\n}\n<\/code><\/pre>\n<p>If i remove the line : <code>( JSONObject json = jsonParser.makeHttpRequest(url_create_user, \"POST\",params); )<\/code> &#8211; of course with intending the try catch out, then the program does not crash, when i press the button that calls the CreateNewUser class.<\/p>\n<p>If i do not do that, my program brings up a loading screen that swirls around until it becomes unresponsive, and asks me to close down the application.<\/p>\n<p>The logs describe Async errors, and illegal state ones:<\/p>\n<pre><code>E\/AndroidRuntime(1132): FATAL EXCEPTION: AsyncTask #2\nE\/AndroidRuntime(1132): Process: com.example.propertypanther, PID: 1132\nE\/AndroidRuntime(1132): java.lang.RuntimeException: An error occured while executing   \ndoInBackground()\nE\/AndroidRuntime(1132):     at android.os.AsyncTask$3.done(AsyncTask.java:300)\nE\/AndroidRuntime(1132):     at  \n java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)\nE\/AndroidRuntime(1132):     at    \njava.util.concurrent.FutureTask.setException(FutureTask.java:222)\nE\/AndroidRuntime(1132):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)\nE\/AndroidRuntime(1132):     at   \nandroid.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)\nE\/AndroidRuntime(1132):     at \njava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)\nE\/AndroidRuntime(1132):     at\n java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)\nE\/AndroidRuntime(1132):     at java.lang.Thread.run(Thread.java:841)\nE\/AndroidRuntime(1132): Caused by: java.lang.IllegalStateException: Target host must not\nbe null, or set in parameters. scheme=null, host=null,    \npath=localhost\/android_connect\/sqlconfig\/create_user.php\nE\/AndroidRuntime(1132):     at   \norg.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.jav\na:591)\nE\/AndroidRuntime(1132):     at  \norg.apache.http.impl.client.DefaultRequestDirector.execute\n(DefaultRequestDirector.java:293)\n\nE\/AndroidRuntime(1132):     at\n org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)\n\nE\/AndroidRuntime(1132):     at    \n org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)\nE\/AndroidRuntime(1132):     at \norg.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)\nE\/AndroidRuntime(1132):     at \ncom.example.propertypanther.JSONParser.makeHttpRequest(JSONParser.java:51)\n\nE\/AndroidRuntime(1132):     at \ncom.example.propertypanther.AddUserActivity$CreateNewUser.doInBackground\n(AddUserActivity.java:116)\n\nE\/AndroidRuntime(1132):     at  \ncom.example.propertypanther.AddUserActivity$CreateNewUser.doInBackground\n(AddUserActivity.java:1)\nE\/AndroidRuntime(1132):     at android.os.AsyncTask$2.call(AsyncTask.java:288)\nE\/AndroidRuntime(1132):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)\nE\/AndroidRuntime(1132):     ... 4 more\nI\/Choreographer(1132): Skipped 82 frames!  The application may be doing too much work on\nits main thread.\nI\/Choreographer(1132): Skipped 58 frames!  The application may be doing too much work on\nits main thread.\nE\/WindowManager(1132): android.view.WindowLeaked: Activity \ncom.example.propertypanther.AddUserActivity has leaked window   \ncom.android.internal.policy.impl.PhoneWindow$DecorView{b1e3d240 V.E..... R.....ID 0,0- \n729,192} that was originally added here\nE\/WindowManager(1132):  at android.view.ViewRootImpl.(ViewRootImpl.java:348)\nE\/WindowManager(1132):  at   \nandroid.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)\nE\/WindowManager(1132):  at  \nandroid.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)\nE\/WindowManager(1132):  at android.app.Dialog.show(Dialog.java:286)\n\nE\/WindowManager(1132):  at \ncom.example.propertypanther.AddUserActivity$CreateNewUser.onPreExecute\n(AddUserActivity.java:97)\n\nE\/WindowManager(1132):  at \n android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)\nE\/WindowManager(1132):  at android.os.AsyncTask.execute(AsyncTask.java:535)\nE\/WindowManager(1132):  at   \ncom.example.propertypanther.AddUserActivity$2.run(AddUserActivity.java:78)\nE\/WindowManager(1132):  at android.os.Handler.handleCallback(Handler.java:733)\nE\/WindowManager(1132):  at android.os.Handler.dispatchMessage(Handler.java:95)\nE\/WindowManager(1132):  at android.os.Looper.loop(Looper.java:136)\nE\/WindowManager(1132):  at android.app.ActivityThread.main(ActivityThread.java:5017)\nE\/WindowManager(1132):  at java.lang.reflect.Method.invokeNative(Native Method)\nE\/WindowManager(1132):  at java.lang.reflect.Method.invoke(Method.java:515)\nE\/WindowManager(1132):  at  \ncom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)\nE\/WindowManager(1132):  at   \ncom.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)\nE\/WindowManager(1132):  at dalvik.system.NativeStart.main(Native Method)\n<\/code><\/pre>\n<p>The script files themselves work as far as i am aware &#8211; besides, the program never executes the script from what i can tell.<\/p>\n<p>If anyone could help me out, i would really appreciate it! I understand you are all busy people, so thank you so much for taking some time out of your day if you do post ideas \ud83d\ude42<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I have been stuck on this problem for a day or two now, so i decided to see if anyone out there could help me. The current goal i have, is to make a HttpPost that connects to, and executes a script that i have on my Wamp server. I have implemented a class that [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-6212","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/6212","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=6212"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/6212\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=6212"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=6212"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=6212"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}