应用程序以Button Click结束

时间:2013-08-02 05:48:18

标签: android database

我的程序包含一个将地点和日期保存到数据库的活动。但是,在点击确定按钮时,应用程序很可能会结束。这里的代码是logcat

FirstActivity.java

package example.showevent1;
import android.os.Bundle;
import android.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class FirstActivity extends FragmentActivity implements OnItemSelectedListener {
    /** Called when the activity is first created. */

    public TextView userSelection;
    public EditText userText;
    private static final String[] items={"Yalahanka","Rajai nagar","Sivaji Nagar","Koramangala","RT Nagar", "Banashankari","Yashwanthpura","Hebbal"};
    DatabaseHandler db = new DatabaseHandler(this);
    public FirstActivity(){

    }

    public FirstActivity(TextView userSelection2, EditText userText2) {
        // TODO Auto-generated constructor stub
        this.userSelection=userSelection;
        this.userText=userText;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        userSelection=(TextView)findViewById(R.id.textView1);
        userText=(EditText)findViewById(R.id.editText1);
        Button okButton = (Button)findViewById(R.id.button1);
         Spinner my_spin=(Spinner)findViewById(R.id.spinner1);//data1
        my_spin.setOnItemSelectedListener(this);
        ArrayAdapter aa=new ArrayAdapter(this, android.R.layout.simple_spinner_item,items);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        my_spin.setAdapter(aa);



    }
    @Override
    public void onItemSelected(AdapterView arg0, View arg1, int pos, long arg3) {
        userSelection.setText(items[pos]);
    }
    @Override
    public void onNothingSelected(AdapterView arg0) {
        // TODO Auto-generated method stub
        userSelection.setText("");
    }
    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getFragmentManager(), "datePicker");
    }
    public String getName(){
        return this.userSelection.toString();
    }
    public String getPhoneNumber(){
        return this.userText.toString();
    }

    public void add_data(View v){
        db.addContact(new FirstActivity(userSelection,userText) );
    }
    }
  

DatePickerFragment.java

package example.showevent1;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.widget.DatePicker;

public class DatePickerFragment extends DialogFragment
                            implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
    }
}

数据库处理程序。我只使用addcontact和getcontact方法

package example.showevent1;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "contactsManager";

    // Contacts table name
    private static final String TABLE_CONTACTS = "contacts";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new contact
    void addContact(FirstActivity contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName()); // Contact Name
        values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone

        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }

    // Getting single contact
    FirstActivity getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        FirstActivity contact = new FirstActivity();
        // return contact
        return contact;
    }

    // Getting All Contacts
 /*   public List<Contact> getAllContacts() {
        List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }

        // return contact list
        return contactList;
    }     */

    // Updating single contact
   /* public int updateContact(FirstActivity contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName());
        values.put(KEY_PH_NO, contact.getPhoneNumber());

        // updating row
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
    }*/

    // Deleting single contact
 /*   public void deleteContact(FirstActivity contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
        db.close();
    }*/


    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

}

activity_first.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@color/color_1"
    tools:context=".FirstActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/spinner1"
        android:layout_below="@+id/spinner1"
        android:layout_marginTop="28dp"
        android:background="#ffff99"
        android:onClick="showDatePickerDialog"
        android:text="@string/dt"
        android:textColor="#b22924" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/spinner1"
        android:layout_alignParentTop="true"
        android:layout_marginTop="31dp"
        android:text="@string/select"
        android:textAlignment="gravity"
        android:textColor="#b22924"
        android:textSize="20sp"
        android:textStyle="bold" />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="36dp"
        android:background="#ffff99"
        android:textColor="#b22924" 
        android:fadingEdge=""/>

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_alignRight="@+id/spinner1"
        android:background="#ffff99"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="56dp"
        android:text="@string/button"
        android:onClick="add_data" />

</RelativeLayout>
  

logcat的

08-02 06:54:04.539: E/AndroidRuntime(1453): FATAL EXCEPTION: main
08-02 06:54:04.539: E/AndroidRuntime(1453): java.lang.IllegalStateException: Could not execute method of the activity
08-02 06:54:04.539: E/AndroidRuntime(1453):     at android.view.View$1.onClick(View.java:3599)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at android.view.View.performClick(View.java:4204)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at android.view.View$PerformClick.run(View.java:17355)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at android.os.Handler.handleCallback(Handler.java:725)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at android.os.Looper.loop(Looper.java:137)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at android.app.ActivityThread.main(ActivityThread.java:5041)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at java.lang.reflect.Method.invokeNative(Native Method)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at java.lang.reflect.Method.invoke(Method.java:511)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at dalvik.system.NativeStart.main(Native Method)
08-02 06:54:04.539: E/AndroidRuntime(1453): Caused by: java.lang.reflect.InvocationTargetException
08-02 06:54:04.539: E/AndroidRuntime(1453):     at java.lang.reflect.Method.invokeNative(Native Method)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at java.lang.reflect.Method.invoke(Method.java:511)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at android.view.View$1.onClick(View.java:3594)
08-02 06:54:04.539: E/AndroidRuntime(1453):     ... 11 more
08-02 06:54:04.539: E/AndroidRuntime(1453): Caused by: java.lang.NullPointerException
08-02 06:54:04.539: E/AndroidRuntime(1453):     at example.showevent1.FirstActivity.getName(FirstActivity.java:57)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at example.showevent1.DatabaseHandler.addContact(DatabaseHandler.java:63)
08-02 06:54:04.539: E/AndroidRuntime(1453):     at example.showevent1.FirstActivity.add_data(FirstActivity.java:64)
08-02 06:54:04.539: E/AndroidRuntime(1453):     ... 14 more

3 个答案:

答案 0 :(得分:1)

在Logcat android.widget.Button cannot be cast to android.widget.EditText

中查看此错误消息

转到FirstActivity.java的第36行。那里你会尝试像

这样的东西

userText = (EditText) findViewById(R.id.editText1);

这里R.id.editText1似乎是Button类型。在这种情况下检查您是否使用了正确的ID,因为您在XML布局文件中指定的名称与您尝试使用的名称相同。

答案 1 :(得分:0)

尝试清理您的项目。有时在布局改变后项目建设被打破。 将数据存储在Activity类中绝对是一种不好的做法,你应该创建一个新类来实现它。

答案 2 :(得分:0)

您的构造函数将userSelection和userText分配给自己而不是传入的值:

public FirstActivity(TextView userSelection2, EditText userText2) {
    // TODO Auto-generated constructor stub
    this.userSelection=userSelection;
    this.userText=userText;
}

这会导致您看到的空指针,因为您正在使用构造函数创建一个新的Activity,但不会分配您提供的值。

第1步:摆脱Activity构造函数。您不应该使用Activity的新实例作为某些联系人数据的持有者,而是导致此级联异常系列。

不是传入整个Activity,而只传入要保存到数据库的TextView或EditTexts的String值,或者创建一个新的“Contact”类来保存状态。