0

I am trying to understand the basic get method in android. I run the following code . But getting a runtime exception. I am not able to understand where exactly the error lies.

MyHttpGetProjectActivity.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MyHttpGetProjectActivity extends Activity implements OnClickListener {

    private EditText usernameEditText;
    private EditText passwordEditText;
    private Button sendGetReqButton;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        usernameEditText = (EditText) findViewById(R.id.e1);
        passwordEditText = (EditText) findViewById(R.id.e2);

        sendGetReqButton = (Button) findViewById(R.id.b1);
        sendGetReqButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        if(v.getId() == R.id.b1){

            // Get the values given in EditText fields
            String givenUsername = usernameEditText.getText().toString();
            String givenPassword = passwordEditText.getText().toString();
            System.out.println("Given usernames is :" + givenUsername + " Given password is :" + givenPassword);

            // Pass those values to connectWithHttpGet() method
            connectWithHttpGet(givenUsername, givenPassword);
        }       
    }

    private void connectWithHttpGet(String givenUsername, String givenPassword) {

        // Connect with a server is a time consuming process.
        //Therefore we use AsyncTask to handle it
        // From the three generic types;
        //First type relate with the argument send in execute()
        //Second type relate with onProgressUpdate method which I haven't use in this code
        //Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method
        class HttpGetAsyncTask extends AsyncTask<String, Void, String>{

            @Override
            protected String doInBackground(String... params) {

                // As you can see, doInBackground has taken an Array of Strings as the argument
                //We need to specifically get the givenUsername and givenPassword
                String paramUsername = params[0];
                String paramPassword = params[1];
                System.out.println("paramUsername is :" + paramUsername + " paramPassword is :" + paramPassword);

                // Create an intermediate to connect with the Internet
                HttpClient httpClient = new DefaultHttpClient();

                // Sending a GET request to the web page that we want
                // Because of we are sending a GET request, we have to pass the values through the URL
                HttpGet httpGet = new HttpGet("http://www.nirmana.lk/hec/android/getLogin.php?paramUsername=" + paramUsername + "&paramPassword=" + paramPassword);

                try {
                    // execute(); executes a request using the default context.
                    // Then we assign the execution result to HttpResponse
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    System.out.println("httpResponse");

                    // getEntity() ; obtains the message entity of this response
                    // getContent() ; creates a new InputStream object of the entity.
                    // Now we need a readable source to read the byte stream that comes as the httpResponse
                    InputStream inputStream = httpResponse.getEntity().getContent();

                    // We have a byte stream. Next step is to convert it to a Character stream
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

                    // Then we have to wraps the existing reader (InputStreamReader) and buffer the input
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                    // InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
                    //The buffer size is 8K
                    //Therefore we need a mechanism to append the separately coming chunks in to one String element
                    // We have to use a class that can handle modifiable sequence of characters for use in creating String
                    StringBuilder stringBuilder = new StringBuilder();

                    String bufferedStrChunk = null;

                    // There may be so many buffered chunks. We have to go through each and every chunk of characters
                    //and assign a each chunk to bufferedStrChunk String variable
                    //and append that value one by one to the stringBuilder
                    while((bufferedStrChunk = bufferedReader.readLine()) != null){
                        stringBuilder.append(bufferedStrChunk);
                    }

                    // Now we have the whole response as a String value.
                    //We return that value then the onPostExecute() can handle the content
                    System.out.println("Returning value of doInBackground :" + stringBuilder.toString());

                    // If the Username and Password match, it will return "working" as response
                    // If the Username or Password wrong, it will return "invalid" as response                  
                    return stringBuilder.toString();

                } catch (ClientProtocolException cpe) {
                    System.out.println("Exception generates caz of httpResponse :" + cpe);
                    cpe.printStackTrace();
                } catch (IOException ioe) {
                    System.out.println("Second exception generates caz of httpResponse :" + ioe);
                    ioe.printStackTrace();
                }

                return null;
            }

            // Argument comes for this method according to the return type of the doInBackground() and
            //it is the third generic type of the AsyncTask
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

                if(result.equals("working")){
                    Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(), "Invalid...", Toast.LENGTH_LONG).show();
                }               
            }           
        }

        // Initialize the AsyncTask class
        HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
        // Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
        // We are passing the connectWithHttpGet() method arguments to that
        httpGetAsyncTask.execute(givenUsername, givenPassword); 

    }
}

Error:-

04-01 02:49:11.744: E/AndroidRuntime(1597): FATAL EXCEPTION: AsyncTask #1
04-01 02:49:11.744: E/AndroidRuntime(1597): Process: com.example.webservicedemo, PID: 1597
04-01 02:49:11.744: E/AndroidRuntime(1597): java.lang.RuntimeException: An error occured while executing doInBackground()
04-01 02:49:11.744: E/AndroidRuntime(1597):     at android.os.AsyncTask$3.done(AsyncTask.java:300)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at java.lang.Thread.run(Thread.java:841)
04-01 02:49:11.744: E/AndroidRuntime(1597): Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at com.example.webservicedemo.MyHttpGetProjectActivity$1HttpGetAsyncTask.doInBackground(MyHttpGetProjectActivity.java:87)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at com.example.webservicedemo.MyHttpGetProjectActivity$1HttpGetAsyncTask.doInBackground(MyHttpGetProjectActivity.java:1)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-01 02:49:11.744: E/AndroidRuntime(1597):     ... 4 more
04-01 02:49:11.744: E/AndroidRuntime(1597): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at libcore.io.Posix.getaddrinfo(Native Method)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
04-01 02:49:11.744: E/AndroidRuntime(1597):     at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
04-01 02:49:11.744: E/AndroidRuntime(1597):     ... 17 more
04-01 02:49:11.744: E/AndroidRuntime(1597): Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
04-01 02:49:11.744: E/AndroidRuntime(1597):     ... 20 more
WannaBeGeek
  • 979
  • 14
  • 32

1 Answers1

0

use internet permission in manifest file

<uses-permission android:name="android.permission.INTERNET" />
raju
  • 785
  • 3
  • 14
  • 28