Android:空指针异常运行时错误

时间:2012-09-28 15:37:34

标签: android nullpointerexception

在我尝试包含菜单,对话框和弹出框后,我开始在启动时收到NullPointerException。我试图注释掉部分代码,只有当我在onCreate方法下面注释类变量和所有内容时,progam才有效。我很感激帮助找到造成异常的原因。

package com.emailandcontactmanager;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

public class MainActivity extends Activity{

EditText title = (EditText) findViewById(R.id.txtTitle);
EditText body = (EditText) findViewById(R.id.txtBody);
View layout = (View) findViewById(R.layout.main);


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

    Button btnSendMenu = (Button) findViewById(R.id.btnSendMenu);
    btnSendMenu.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent sendMenu = new Intent(v.getContext(), SendMenu.class);
        startActivity(sendMenu);
    }
    });

    Button btnContactsMenu = (Button) findViewById(R.id.btnContactsMenu);
    btnContactsMenu.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent contactsMenu = new Intent(v.getContext(), ContactsMenu.class);
        startActivity(contactsMenu);
    }
    });        

    Button btnTemplatesMenu = (Button) findViewById(R.id.btnTemplatesMenu);
    btnTemplatesMenu.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent templatesMenu = new Intent(v.getContext(), TemplatesMenu.class);
        startActivity(templatesMenu);
    }
    });

    Button btnTagsMenu = (Button) findViewById(R.id.btnTagsMenu);
    btnTagsMenu.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Intent tagsMenu = new Intent(v.getContext(), TagsMenu.class);
        startActivity(tagsMenu);
    }
    });

}//end onCreate

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int which) { 
        switch (which){ 
        case DialogInterface.BUTTON_POSITIVE: 
            finish();
            break; 

        case DialogInterface.BUTTON_NEGATIVE: 
            //No button clicked 
            break; 
        } 
    } 
}; 

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.help:     showPopup(this);
                            break;

        case R.id.back:     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
                            builder.setMessage("Are you     sure?").setPositiveButton("Yes", dialogClickListener) 
                            .setNegativeButton("No", dialogClickListener).show(); 
                            break;
    }
    return true;
}

private void showPopup(final Activity context){
    int popupWidth = 200;
    int popupHeight = 150;

    // change title and body based on button
    onHelpClick(layout);

    LinearLayout viewGroup = (LinearLayout) this.findViewById(R.id.popup);
    LayoutInflater layoutInfalter = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View layout = layoutInfalter.inflate(R.layout.popup, viewGroup);

    final PopupWindow popup = new PopupWindow();
    popup.setContentView(layout);
    popup.setWidth(popupWidth);
    popup.setHeight(popupHeight);
    popup.setFocusable(true);



    Button close = (Button) layout.findViewById(R.id.close);
            close.setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    popup.dismiss();
                }
            });

}


private void onHelpClick(View v) {

    switch(v.getId())
    {
    case R.id.btnSendMenu:
        title.setText("Send Menu");
        body.setText("Opens the send menu where you can send an email.");
        break;
    case R.id.btnContactsMenu:
        title.setText("Contacts Menu");
        body.setText("Opens the contact menu where you can add a contact or select from a list of" +
                "recored contacts to edit or view.");
        break;
    case R.id.btnTemplatesMenu:
        title.setText("Templates Menu");
        body.setText("Opens the templates menu where you can add an email template or select from a list of" +
        " recorded templates to edit or view.");
        break;
    case R.id.btnTagsMenu:
        title.setText("Tags Menu");
        body.setText("Opens the tags menu where you can add a tag used for sorting contacs, or select from a list of" +
        " recorded tags to edit or view.");
        break;
    default:
        throw new RuntimeException("Unknown button ID");
    }

}

}//end Class

logcat消息是:

09-28 15:07:49.205: D/AndroidRuntime(1403): Shutting down VM
09-28 15:07:49.245: W/dalvikvm(1403): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
09-28 15:07:49.365: E/AndroidRuntime(1403): FATAL EXCEPTION: main
09-28 15:07:49.365: E/AndroidRuntime(1403): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.emailandcontactmanager/com.emailandcontactmanager.MainActivity}: java.lang.NullPointerException
09-28 15:07:49.365: E/AndroidRuntime(1403):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1879)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at android.app.ActivityThread.access$600(ActivityThread.java:122)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at android.os.Looper.loop(Looper.java:137)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at android.app.ActivityThread.main(ActivityThread.java:4340)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at java.lang.reflect.Method.invokeNative(Native Method)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at java.lang.reflect.Method.invoke(Method.java:511)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at dalvik.system.NativeStart.main(Native Method)
09-28 15:07:49.365: E/AndroidRuntime(1403): Caused by: java.lang.NullPointerException
09-28 15:07:49.365: E/AndroidRuntime(1403):     at android.app.Activity.findViewById(Activity.java:1794)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at com.emailandcontactmanager.MainActivity.<init>(MainActivity.java:24)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at java.lang.Class.newInstanceImpl(Native Method)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at java.lang.Class.newInstance(Class.java:1319)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
09-28 15:07:49.365: E/AndroidRuntime(1403):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1870)
09-28 15:07:49.365: E/AndroidRuntime(1403):     ... 11 more

告诉我你是否还需要像xml文件代码那样的东西。我感谢任何帮助。

1 个答案:

答案 0 :(得分:6)

问题是您在Activity的布局被夸大之前尝试使用findViewById查找视图。在Android开发者文档中了解有关Activities的活动生命周期的更多信息。

请改为:

public class MainActivity extends Activity{

    private EditText title;
    private EditText body;
    private View layout;

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

        title = (EditText) findViewById(R.id.txtTitle);
        body = (EditText) findViewById(R.id.txtBody);
        // also , the line below is incorrect, the findViewById method requires
        // that you use an id(R.id.somthing) and not a layout resource like you do
        layout = (View) findViewById(R.layout.main);

        // Rest of your code.