0

I am doing an android application for our capstone project. I am trying to make the only button I put in the home screen for login purposes. Apparently, my code is not yet finish as this is only for checking of the user account which means I do not use intents yet to go to another screen. Upon clicking this certain button (id is loginBtn), I am catching a "null pointer exception". Any help would be greatly appreciated.

Here is the MainActivity class

package com.feufern.apms;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

    //login
    Button b;
    EditText et,pass;
    TextView tv;
    RadioGroup radioUserGroup;
    RadioButton radioUserButton;

    //json
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;
    ProgressDialog dialog = null;

    //session
    public static String student_id;

    //slideshow variables
    public int imageIndex=0;
    Timer timer;
    TimerTask task;
    ImageView slidingImages;
    //end of slideshow variables

    private int[] IMAGE_ID = {R.drawable.slide1, R.drawable.slide2, R.drawable.slide3, R.drawable.slide4};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        try{
        super.onCreate(savedInstanceState);
        this.setTitle("Welcome");
        setContentView(R.layout.activity_main);

        //login codes
            b = (Button) findViewById(R.id.loginBtn);
            et = (EditText)findViewById(R.id.username);
            pass= (EditText)findViewById(R.id.password);

            b.setOnClickListener(this);

        }catch(Exception e){
            Toast.makeText(getApplicationContext(),
                      "Error..." + e.getMessage(), Toast.LENGTH_LONG).show();
        }

       try{
        //start of code for slideshow
        final Handler mHandler = new Handler(); 
        final Runnable mUpdateResults = new Runnable() {
            public void run() {
                SlideShow();
            }
        };


        int delay = 200; //1sec
        int period = 4000; //3sec
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
                public void run() {
                    mHandler.post(mUpdateResults);
                }
        }, delay, period);
        //end of code for slideshow
       }catch(Exception e){
           Toast.makeText(getApplicationContext(),
                      "Error..." + e.getMessage(), Toast.LENGTH_LONG).show();
       }
    }

    private void SlideShow() { 
        slidingImages = (ImageView)findViewById(R.id.slideBanner);
        slidingImages.setImageResource(IMAGE_ID[imageIndex%IMAGE_ID.length]);
        imageIndex++;     
        Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
        slidingImages.startAnimation(fadeInAnimation);
    }

    void login(){
        try{            

            httpclient=new DefaultHttpClient();
            httppost= new HttpPost("http://10.0.2.2/mobile/check.php"); 
            //add your data
            nameValuePairs = new ArrayList<NameValuePair>(2);
            // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
            nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
            nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim())); 
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //Execute HTTP Post Request
            response=httpclient.execute(httppost);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpclient.execute(httppost, responseHandler);
            System.out.println("Response : " + response); 


            if(response.equalsIgnoreCase("User Found")){
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(MainActivity.this,"Login Success", Toast.LENGTH_SHORT).show();

                    }
                });

                startActivity(new Intent(MainActivity.this, MenuPage.class));
                student_id = et.getText().toString().trim();
            }else{
                startActivity(new Intent(MainActivity.this, MenuPage.class));
                student_id = et.getText().toString().trim();        
            }

        }catch(Exception e){
            dialog.dismiss();
            System.out.println("Exception : " + e.getMessage());
        }
    }
    void showAlert(){
        try{
        MainActivity.this.runOnUiThread(new Runnable() {
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Login Error.");
                builder.setMessage("User not Found.")  
                       .setCancelable(false)
                       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {

                           }
                       });                     
                AlertDialog alert = builder.create();
                alert.show();               
            }
        });
        }catch(Exception e){
            Toast.makeText(getApplicationContext(),
                      "Error..." + e.toString(), Toast.LENGTH_LONG).show();

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId()){  
        case R.id.loginBtn:
            try{

            login();
            }catch(Exception e){
                 Toast.makeText(getApplicationContext(),
                          "Error..." + e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    }


}

the activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center|center_vertical"
    android:background="@color/firstbgcolor"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:src="@drawable/banner" />

    <ImageView
        android:id="@+id/slideBanner"
        android:layout_width="match_parent"
        android:layout_height="177dp"
        android:adjustViewBounds="true"
        android:src="@drawable/slide1" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="23dp" >
    </FrameLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="0.51" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <FrameLayout
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="0.08" >

            </FrameLayout>

            <ScrollView
                android:id="@+id/scrollView1"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="0.18" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical" >

                    <TextView
                        android:id="@+id/textView1"
                        android:layout_width="103dp"
                        android:layout_height="wrap_content"
                        android:text="Username"
                        android:textAppearance="?android:attr/textAppearanceSmall" />

                    <EditText
                        android:id="@+id/username"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content" >

                        <requestFocus />
                    </EditText>

                    <TextView
                        android:id="@+id/textView2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Password"
                        android:textAppearance="?android:attr/textAppearanceSmall" />

                    <EditText
                        android:id="@+id/password"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:ems="10"
                        android:inputType="textPassword" />

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content" >

                        <TextView
                            android:id="@+id/textView3"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_weight="0.74"
                            android:text="Login as: "
                            android:textAppearance="?android:attr/textAppearanceSmall" />
                    </LinearLayout>

                    <Button
                        android:id="@+id/loginBtn"
                        style="?android:attr/buttonStyleSmall"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:text="Login" />
                </LinearLayout>

            </ScrollView>

            <FrameLayout
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="0.08" >
            </FrameLayout>

        </LinearLayout>
    </FrameLayout>

</LinearLayout>

and the manifest file

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.feufern.apms"
    android:versionCode="1"
    android:versionName="1.0" xmlns:tools="http://schemas.android.com/tools">

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="14" tools:ignore="OldTargetApi"/>

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application
        android:allowBackup="true"
        android:icon="@drawable/logo"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:screenOrientation="portrait"
            android:name="com.feufern.apms.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity 
           android:screenOrientation="portrait"
           android:name=".MenuPage"
           android:label="@string/app_name" />

    </application>

</manifest>

I don't know why I'm getting this error. :( Please help. Thanks!

4
  • are you sure you are getting a NPE and not the NetworkOnMainThreadException? Commented Oct 20, 2013 at 20:29
  • such long piece of code without line numbers and without exception stack specifying line of exception. Ahhhhh painful. Search that line at your end. and see the objects in that statements are initialized and are not null before calling any method on it. Commented Oct 20, 2013 at 20:32
  • @blackbelt Yes I'm sure of it since I used try/catch blocks Commented Oct 20, 2013 at 20:32
  • @blackbelt I am getting the said exception now. Commented Oct 20, 2013 at 21:04

1 Answer 1

1

You are getting NullPointerException at below line

dialog.dismiss(); 

Since you have not initialized dialog.

Further catching generic exception is not a good practice. It is suppressing some other bug. So check your logs why your code enters the exception handler where dismiss is called

Sign up to request clarification or add additional context in comments.

2 Comments

thanks @nandeesh. but now I am getting network on main thread exception. honestly I didn't quite grasp the knowledge of using threads in android.
Since network operations can potentially take a long time, you need to run them on a seperate thread to avoid blocking the UI - resulting in a Application Not Responding error. You could also use AsyncTask

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.