1

I have used the following code but it gives error when executing the Asyntask and also I have posted my JsonParser class.Please guide me how can i remove this error.

        public class Login extends Activity implements OnClickListener {

            private EditText user, pass;
            private Button mSubmit, mRegister;
            private ProgressDialog pDialog;
            // JSON parser class
            JSONParser jsonParser = new JSONParser();
             private static final String LOGIN_URL = "http://******/web_service/index.php";
           //www.itsoft-solutions.net
            //JSON element ids from repsonse of php script:
            private static final String TAG_SUCCESS = "success";
            private static final String TAG_MESSAGE = "message";
            public static String uname;
            public static String password;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                // TODO Auto-generated method stub
                super.onCreate(savedInstanceState);
                setContentView(R.layout.login);
                String uName, pwd;
                //setup input fields
                user = (EditText) findViewById(R.id.username);
                pass = (EditText) findViewById(R.id.password);
                //setup buttons
                mSubmit = (Button) findViewById(R.id.login);
                mRegister = (Button) findViewById(R.id.register);
                //register listeners
                mSubmit.setOnClickListener(this);
                mRegister.setOnClickListener(this);

            }

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                switch (v.getId()) {
                    case R.id.login:
                         new AttemptLogin(user.getText().toString(), pass.getText().toString()).execute();
                        break;
                    case R.id.register:
                        Intent i = new Intent(this, Register.class);
                        startActivity(i);
                        break;

                    default:
                        break;
                }
            }

and I have also posted my Asyntask class

            class AttemptLogin extends AsyncTask<String, String, String> {

                boolean failure = false;
                String uName, pwd;
                public AttemptLogin(String userName, String password) {
                    uName = userName;
                    pwd = password;
                }

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    pDialog = new ProgressDialog(Login.this);
                    pDialog.setMessage("Attempting login...");
                    pDialog.setIndeterminate(false);
                    pDialog.setCancelable(true);
                    pDialog.show();
                }

                @Override
                protected String doInBackground(String... args) {
                    // TODO Auto-generated method stub
                    // Check for success tag
                    int success;

                    try {
                        // Building Parameters
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair("username", uName));
                        params.add(new BasicNameValuePair("password", pwd));

                        Log.d("request!", "starting");
                        // getting product details by making HTTP request
                        JSONObject json = jsonParser.makeHttpRequest(
                                LOGIN_URL, "POST", params);

                        // check your log for json response
                        Log.d("Login attempt", json.toString());

                        // json success tag
                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            Log.d("Login Successful!", json.toString());
                            Intent i = new Intent(Login.this, ReadComments.class);
                            finish();
                            startActivity(i);
                            return json.getString(TAG_MESSAGE);
                        } else {
                            Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                            return json.getString(TAG_MESSAGE);

                        }
                    } 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
                    pDialog.dismiss();
                    if (file_url != null) {
                        Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
                    }

                }

            }

        }

The following code in the JSONParser.java

        package com.example.mysqltest;

        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 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;

            }
        }

I have included the following library to my project.

    1. httpclient-4.5.jar
    2. httpcore-4.4.1.jar

Below is the error stack.

        09-01 14:22:44.365  16257-16869/com.example.mysqltest E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #3
            Process: com.example.mysqltest, PID: 16257
            java.lang.RuntimeException: An error occured while executing doInBackground()
                    at android.os.AsyncTask$3.done(AsyncTask.java:300)
                    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                    at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                    at java.lang.Thread.run(Thread.java:818)
             Caused by: java.lang.NoSuchMethodError: No virtual method execute(Lorg/apache/http/client/methods/HttpUriRequest;)Lorg/apache/http/client/methods/CloseableHttpResponse; in class Lorg/apache/http/impl/client/DefaultHttpClient; or its super classes (declaration of 'org.apache.http.impl.client.DefaultHttpClient' appears in /system/framework/ext.jar)
                    at com.example.mysqltest.JSONParser.makeHttpRequest(JSONParser.java:52)
                    at com.example.mysqltest.Login$AttemptLogin.doInBackground(Login.java:136)
                    at com.example.mysqltest.Login$AttemptLogin.doInBackground(Login.java:96)
                    at android.os.AsyncTask$2.call(AsyncTask.java:288)
                    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                    at java.lang.Thread.run(Thread.java:818)
1
  • 1
    Httpclient is deprecated one, so better use URLConnection or Volley Commented Sep 1, 2015 at 9:49

2 Answers 2

6

in build.gradle android section put this code
useLibrary 'org.apache.http.legacy'

Then your application will use org.apache.http.legacy.jar which is in Android/Sdk/platforms/android-23/optional. The reason for crash is that google removed support of Apache HTTP client and suggests using unstead HttpURLConnection class.

Here's a sample how to get content of some url using HttpURLConnection (it can be http://google.com?hacked=true, for example):

public static String file_get_contents(String fileURL)
        throws Exception {

    Log.d("file_get_contents", "getting url " + fileURL);
    String result = "";
    URL url = new URL(fileURL);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    int responseCode = httpConn.getResponseCode();

    // always check HTTP response code first
    if (responseCode == HttpURLConnection.HTTP_OK) {
        String fileName = "";
        String disposition = httpConn.getHeaderField("Content-Disposition");
        String contentType = httpConn.getContentType();
        int contentLength = httpConn.getContentLength();

        if (disposition != null) {
            // extracts file name from header field
            int index = disposition.indexOf("filename=");
            if (index > 0) {
                fileName = disposition.substring(index + 10,
                        disposition.length() - 1);
            }
        } else {
            // extracts file name from URL
            fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
                    fileURL.length());
        }

        Log.d("file_get_contents", "Content-Type = " + contentType);
        Log.d("file_get_contents", "Content-Disposition = " + disposition);
        Log.d("file_get_contents", "Content-Length = " + contentLength);
        Log.d("file_get_contents", "fileName = " + fileName);

        // opens input stream from the HTTP connection
        InputStream inputStream = httpConn.getInputStream();

        int bytesRead = -1;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            Log.d("file_get_contents", "bytes read: " + bytesRead);
            String bufferString = new String(buffer, 0, bytesRead, "UTF-8");
            Log.d("file_get_contents", "buffer string: " + bufferString);
            result = result.concat(bufferString);
            //outputStream.write(buffer, 0, bytesRead);
        }

        //outputStream.close();
        inputStream.close();

        Log.d("file_get_contents", "File downloaded");
    } else {
        Log.d("file_get_contents", "No file to download. Server replied HTTP code: " + responseCode);
    }
    httpConn.disconnect();

    Log.d("file_get_contents", "returning " + result);
    return result;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Adding the line to the gradle file worked perfectly.
1

Please try using following version

HttpClient : httpclient-4.0-beta2.jar HttpCore : httpcore-4.1.jar

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.