单击按钮显示空指针异常错误

时间:2013-10-20 20:24:10

标签: java android mobile

我正在为我们的顶点项目做一个Android应用程序。我正在尝试将我放在主屏幕中的唯一按钮用于登录目的。显然,我的代码还没有完成,因为这只是用于检查用户帐户,这意味着我还没有使用意图去另一个屏幕。单击此特定按钮(id为loginBtn)后,我正在捕获“空指针异常”。任何帮助将不胜感激。

这是MainActivity类

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();
            }
        }
    }


}

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>

和清单文件

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

我不知道为什么我会收到这个错误。 :(请帮忙。谢谢!

1 个答案:

答案 0 :(得分:1)

你在下面的行

获得NullPointerException
dialog.dismiss(); 

由于您尚未初始化对话框。

进一步捕捉一般异常不是一个好习惯。它抑制了一些其他的bug。因此,请检查您的日志,为什么您的代码进入了异常处理程序,其中调用了dismiss