调用onClickListerner()

时间:2016-11-13 12:39:14

标签: android

调用saveDetails()函数时,应用程序总是崩溃。不知道是什么主要原因。我弄清楚了。有人,请帮帮我。

当我删除saveDetails()函数时,app会完美启动并在单击imageButton时调用contact_details布局。但是当添加该功能时,应用程序就会崩溃。该日志在saveButton.setOnClickListener()上显示错误。

package com.bikram.contacts;

import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {

    DatabaseHelper databaseHelper;
    EditText firstName, lastName, phoneNumber;
    ImageButton imageButton;
    Button saveButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        databaseHelper = new DatabaseHelper(this);


        firstName = (EditText) findViewById(R.id.first_name);
        lastName = (EditText) findViewById(R.id.last_name);
        phoneNumber = (EditText) findViewById(R.id.phone_number);
        imageButton = (ImageButton) findViewById(R.id.imageButton);
        saveButton = (Button) findViewById(R.id.save_button);

        viewName();
        addContacts();
        saveDetails();

    }

    public void saveDetails() {
        saveButton.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                }
        );
    }

    public void addContacts() {
        imageButton.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setContentView(R.layout.contact_details);
                    }
                }
        );
    }

    public void viewName() {
        Cursor result = databaseHelper.getName();
        ArrayList arrayList = new ArrayList();
        while (result.moveToNext()) {
            arrayList.add(result.getString(0));
            arrayList.add(result.getString(1));
        }
        ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.text_view, arrayList);

        ListView listView = (ListView) findViewById(R.id.display_full_name);
        listView.setAdapter(arrayAdapter);
    }
}

DatabaseHelper.java

package com.bikram.contacts;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Sabina on 13-Nov-16.
 */

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String databaseName = "Contact.db";
    public static final String tableName = "contact_details";
    public static final String col_1 = "First Name";
    public static final String col_2 = "Last Name";
    public static final String col_3 = "Mobile Number";

    public DatabaseHelper(Context context) {
        super(context, databaseName, null, 4);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("Create table " + tableName + "(First Name Text, Last Name Text, Mobile Number Number Not Null Primary Key);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("Drop table if exists" + tableName);
        onCreate(db);
    }

    public Cursor getName() {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "Select First Name, Last Name from " + tableName;
        Cursor result = db.rawQuery(query, null);
        return result;
    }

    public boolean addContactDetails(String firstName, String lastName, String phoneNumber){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(col_1, firstName);
        contentValues.put(col_2, lastName);
        contentValues.put(col_3, phoneNumber);

        long result = db.insert(tableName, null, contentValues);

        if(result == -1)
            return false;
        else
            return true;
    }
}

从android Monitor

登录
11-13 18:27:49.343 2108-2108/com.bikram.contacts W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41fd7ce0)
11-13 18:27:49.343 2108-2108/com.bikram.contacts W/dalvikvm: threadid=1: uncaught exception occurred
11-13 18:27:49.344 2108-2108/com.bikram.contacts W/System.err: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bikram.contacts/com.bikram.contacts.MainActivity}: java.lang.NullPointerException
11-13 18:27:49.345 2108-2108/com.bikram.contacts W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2347)
11-13 18:27:49.345 2108-2108/com.bikram.contacts W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2399)
11-13 18:27:49.345 2108-2108/com.bikram.contacts W/System.err:     at android.app.ActivityThread.access$800(ActivityThread.java:160)
11-13 18:27:49.345 2108-2108/com.bikram.contacts W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
11-13 18:27:49.346 2108-2108/com.bikram.contacts W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:110)
11-13 18:27:49.346 2108-2108/com.bikram.contacts W/System.err:     at android.os.Looper.loop(Looper.java:193)
11-13 18:27:49.346 2108-2108/com.bikram.contacts W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5330)
11-13 18:27:49.346 2108-2108/com.bikram.contacts W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
11-13 18:27:49.346 2108-2108/com.bikram.contacts W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
11-13 18:27:49.346 2108-2108/com.bikram.contacts W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
11-13 18:27:49.347 2108-2108/com.bikram.contacts W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
11-13 18:27:49.347 2108-2108/com.bikram.contacts W/System.err:     at dalvik.system.NativeStart.main(Native Method)
11-13 18:27:49.347 2108-2108/com.bikram.contacts W/System.err: Caused by: java.lang.NullPointerException
11-13 18:27:49.348 2108-2108/com.bikram.contacts W/System.err:     at com.bikram.contacts.MainActivity.saveDetails(MainActivity.java:44)
11-13 18:27:49.348 2108-2108/com.bikram.contacts W/System.err:     at com.bikram.contacts.MainActivity.onCreate(MainActivity.java:39)
11-13 18:27:49.348 2108-2108/com.bikram.contacts W/System.err:     at android.app.Activity.performCreate(Activity.java:5264)
11-13 18:27:49.348 2108-2108/com.bikram.contacts W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
11-13 18:27:49.348 2108-2108/com.bikram.contacts W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
11-13 18:27:49.348 2108-2108/com.bikram.contacts W/System.err:  ... 11 more
11-13 18:27:49.348 2108-2108/com.bikram.contacts W/dalvikvm: threadid=1: calling UncaughtExceptionHandler
11-13 18:27:49.350 2108-2108/com.bikram.contacts E/AndroidRuntime: FATAL EXCEPTION: main
                                                                   Process: com.bikram.contacts, PID: 2108
                                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bikram.contacts/com.bikram.contacts.MainActivity}: java.lang.NullPointerException
                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2347)
                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2399)
                                                                       at android.app.ActivityThread.access$800(ActivityThread.java:160)
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:110)
                                                                       at android.os.Looper.loop(Looper.java:193)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5330)
                                                                       at java.lang.reflect.Method.invokeNative(Native Method)
                                                                       at java.lang.reflect.Method.invoke(Method.java:515)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
                                                                       at dalvik.system.NativeStart.main(Native Method)
                                                                    Caused by: java.lang.NullPointerException
                                                                       at com.bikram.contacts.MainActivity.saveDetails(MainActivity.java:44)
                                                                       at com.bikram.contacts.MainActivity.onCreate(MainActivity.java:39)
                                                                       at android.app.Activity.performCreate(Activity.java:5264)
                                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2399) 
                                                                       at android.app.ActivityThread.access$800(ActivityThread.java:160) 
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1330) 
                                                                       at android.os.Handler.dispatchMessage(Handler.java:110) 
                                                                       at android.os.Looper.loop(Looper.java:193) 
                                                                       at android.app.ActivityThread.main(ActivityThread.java:5330) 
                                                                       at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                       at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829) 
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645) 
                                                                       at dalvik.system.NativeStart.main(Native Method) 
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5: SuspendAll starting
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5:   threadid=1 status=7 sc=1 dc=0
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5:   threadid=11 status=7 sc=1 dc=0
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5:   threadid=10 status=7 sc=1 dc=0
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5:   threadid=9 status=7 sc=1 dc=0
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5:   threadid=8 status=4 sc=1 dc=0
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5:   threadid=7 status=4 sc=1 dc=0
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5:   threadid=6 status=4 sc=1 dc=0
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5:   threadid=4 status=8 sc=1 dc=0
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5:   threadid=3 status=8 sc=1 dc=0
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5:   threadid=2 status=8 sc=1 dc=0
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5: SuspendAll complete : 1
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5: ResumeAll starting
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5: ResumeAll waking others
11-13 18:27:54.661 2108-2116/com.bikram.contacts D/dalvikvm: threadid=5: ResumeAll complete

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/display_full_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="35dp"
        android:layout_marginRight="25dp"
        android:padding="5dp"
        app:srcCompat="@mipmap/add_button" />

</RelativeLayout>

contact_details.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="New Contact" />

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

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

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

    <Button
        android:id="@+id/save_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:elevation="12dp"
        android:text="Save" />
</LinearLayout>

text_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id = "@+id/textView"/>

</LinearLayout>

2 个答案:

答案 0 :(得分:3)

您尝试在同一活动中使用两种布局。 activity_main.xml已加载onCreate,但它不包含ID为Button的{​​{1}}。因此,当您致电save_button时,saveButton = (Button) findViewById(R.id.save_button);的结果值为saveButton

稍后,在null中,您设置为在点击按钮时将活动的内容视图更改为addContacts。此布局包含contact_details,其ID为Button,但您不能再次调用save_button,因此findViewById变量仍为saveButton。即使你这样做了,问题仍然会出现,因为崩溃发生在点击按钮之前。

您发现崩溃的原因是因为在调用null后,您继续调用addContacts方法,该方法会尝试在saveDetails变量上调用方法。如上所述,变量包含saveButton,因此NPE和崩溃。

我建议不要在单个活动中使用多个内容视图。考虑创建一个新活动来处理联系人详细信息条目,并在按下添加按钮时启动它。如果您不想为此使用活动,则可以轻松地使用片段。

答案 1 :(得分:0)

您必须在activity_main.xml中包含contact_details。上面的@clownba0t已经解释了原因。