0

While executing the below code I am getting a NullPointerException in the class LoginAuthenticate in try block while closing the stream.

I am using an AsyncTask and am activating it from the onClick on the Button.

On the onClick I am calling the login auth and in try block getting an exception.

public class DattabActivity extends Activity implements View.OnClickListener {
    /** Called when the activity is first created. */    
    private final static String SERVICE_URI = "http://182.50.154.23/Dattab.Device.Rest/ServiceClass/RestDeviceService.svc";

        @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v("DEBUG", "DattabActivity");        
        setContentView(R.layout.login);
        Button loginbutton=(Button)findViewById(R.id.loginbtn);
        loginbutton.setOnClickListener(this);

        Intent available=new Intent();
        available.setClass(DattabActivity.this, Available_Surveys.class);         

    }

    public void onClick(View v) {
        switch(v.getId()){

        case R.id.loginbtn:
            // TODO Auto-generated method stub
            EditText userid = (EditText)findViewById(R.id.useredt);
            EditText passwd = (EditText)findViewById(R.id.pwdedt);

            Log.i("DEBUG", "DattabActivity Click Button ");

            userid.setText("surveyor1");
            passwd.setText("dev");
            if(userid.getText().toString()=="" ||passwd.getText().toString()==""){

                Toast.makeText(getApplicationContext(), "Please enter your account details", Toast.LENGTH_LONG).show();
            }
            else{
                    String params = SERVICE_URI + "/authenticateuser/"+userid.getText().toString()+"/"+passwd.getText().toString();
                    try {
                            LoginAuthenticate la = new LoginAuthenticate();
                            la.execute(params);
                            la.get();


                        JSONObject json = new JSONObject(new String(la.getStreamBuffer()));
                        Intent available=new Intent();
                        available.setClass(DattabActivity.this, Available_Surveys.class);
                        available.putExtra("userid", json.getString("SurveyorId"));
                        startActivity(available);
                        Toast.makeText(getApplicationContext(), json.getString("SurveyorId"),Toast.LENGTH_LONG).show();
                        Toast.makeText(getApplicationContext(), "Login Clicked", Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    catch(Exception e){
                        e.printStackTrace();
                    }



            }

            break ;
        }

    }
    private class LoginAuthenticate extends AsyncTask<String,Integer,char[]> {
        private char[] streamBuffer ;
        @Override
        protected char[] doInBackground(String... params) {
            android.os.Debug.waitForDebugger();

            String url=params[0];
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet request = new HttpGet(url);
            try {
                    request.setHeader("Accept", "application/json");
                    request.setHeader("Content-type", "application/json");
                    HttpResponse response = httpClient.execute(request);
                    HttpEntity responseEntity = response.getEntity();

                    // Read response data into buffer
                    char[] buffer = new char[(int)responseEntity.getContentLength()];
                    InputStream stream = responseEntity.getContent();
                    InputStreamReader reader = new InputStreamReader(stream);
                    reader.read(buffer);
                    stream.close();//here it goes in catch NULL Pointer
                    return buffer ;

            }catch(Exception e){
                e.printStackTrace();
                return null;
            }

        }
        protected void onPostExecute(char[] result){
            streamBuffer = result ;
        }

        public char[] getStreamBuffer(){
            return streamBuffer ;
        }
    }
}
Sufian
  • 6,405
  • 16
  • 66
  • 120
Kumar Vishal
  • 121
  • 1
  • 9

2 Answers2

0

Try this to handle the null exception error.

        try {
                request.setHeader("Accept", "application/json");
                request.setHeader("Content-type", "application/json");
                HttpResponse response = httpClient.execute(request);
                HttpEntity responseEntity = response.getEntity();

                // Read response data into buffer
                char[] buffer = new char[(int)responseEntity.getContentLength()];
                try{
                      InputStream stream = responseEntity.getContent();
                       InputStreamReader reader = new InputStreamReader(stream);
                        reader.read(buffer);
                 }
                 finally{
                       stream.close();//here it goes in catch NULL Pointer
                  }
                return buffer ;

        }catch(Exception e){
            e.printStackTrace();
            return null;
        }

Link: https://stackoverflow.com/a/156889/1503155

Community
  • 1
  • 1
Lazy Ninja
  • 22,342
  • 9
  • 83
  • 103
  • Actually is always I am not able to understand what I am doing wrong in doInbackGround I am taking stream and onPostExecute I am updating it and through getStreamBuffer() I am trying to use it on UI thread to updated UI but every time its goes in catch while closing the stream in try block and retun NULL so every time it throw NULL pointer exception So basic why it goes to catch block every time . – Kumar Vishal Aug 02 '12 at 08:04
0

There are many reasons that HTTP returns null pointer exception. Your internet is not working, The URL you are hitting does not exist, or no longer exist. In your try catch block you are doing something wrong which is causing exception, and your catch blocks catches every exception always return null pointer.

If you are testing on emulator, and you are sure, that the URL is correct and nothing is wrong in your code, you can disbale/enable your internet connection, and clean the project and rebuild, and restart emulator. Sometimes it fixes the Internet issue in emulator.

Adeel Pervaiz
  • 1,336
  • 10
  • 11