在android中的SQLite数据库中插入记录时的运行时异常

时间:2014-02-04 19:08:44

标签: android database sqlite

我正在尝试从用户那里获得三个输入(名字,姓氏,金额)。这三个都是字符串。我想将它插入SQLite数据库,但它给出了运行时异常。以下是我的代码:

Contact.java

public class Contact {  
    int _id;  
    String _fname;  
    String _lname;
    String _amount;

     public Contact(){   }  
    public Contact(int id, String fname, String lname , String amount){  
        this._id = id;  
        this._fname = fname;  
        this._lname = lname;
        this._amount = amount;
    }  

    public Contact(String fname, String lname , String amount){  
         this._fname = fname;  
            this._lname = lname;
            this._amount = amount;
    }  
    public int getID(){  
        return this._id;  
    }  

    public void setID(int id){  
        this._id = id;  
    }  

    public String getfName(){  
        return this._fname;  
    }  

    public void setfName(String fname){  
        this._fname = fname;  
    }  


    public String getlName(){  
        return this._lname;  
    }  

    public void setlName(String lname){  
        this._lname = lname;  
    }  


    public String getAmount(){  
        return this._amount;  
    }  

    public void setAmount(String amount){  
        this._amount = amount;  
    }  
}  

DatabaseHandler.java

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 {  
private static final int DATABASE_VERSION = 1;  
private static final String DATABASE_NAME = "ngo";  
private static final String TABLE_CONTACTS = "customer";  
 private static final String KEY_ID = "id";  
private static final String KEY_FNAME = "fname"; 
private static final String KEY_LNAME = "lname"; 
private static final String KEY_AMOUNT = "amount";  

public DatabaseHandler(Context context) {  
    super(context, DATABASE_NAME, null, DATABASE_VERSION);  
    //3rd argument to be passed is CursorFactory instance  
}  

// Creating Tables  
@Override  
public void onCreate(SQLiteDatabase db) {  
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("  
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_FNAME + " TEXT," + KEY_LNAME + " TEXT,"  
            + KEY_AMOUNT + " 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);  
}  

 // code to add the new contact  
 void addContact(Contact contact) {  
    SQLiteDatabase db = this.getWritableDatabase();  

    ContentValues values = new ContentValues();  
    values.put(KEY_FNAME, contact.getfName()); // Contact first Name  
    values.put(KEY_LNAME, contact.getlName()); // Contact first Name  
    values.put(KEY_AMOUNT, contact.getAmount()); // Contact amount  

    // Inserting Row  
    db.insert(TABLE_CONTACTS, null, values);  
    //2nd argument is String containing nullColumnHack  
    db.close(); // Closing database connection  
}  

// code to get the single contact  
Contact getContact(int id) {  
    SQLiteDatabase db = this.getReadableDatabase();  

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

    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),  
            cursor.getString(1), cursor.getString(2),cursor.getString(3));  
    // return contact  
    return contact;  
}  

// code to get all contacts in a list view  
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.setfName(cursor.getString(1)); 
            contact.setlName(cursor.getString(2)); 
            contact.setAmount(cursor.getString(3));  
            // Adding contact to list  
            contactList.add(contact);  
        } while (cursor.moveToNext());  
    }  

    // return contact list  
    return contactList;  
}       
}  

MainActivity.java

import java.util.List;  

import android.os.Bundle;  
import android.app.Activity;  
import android.util.Log;  
import android.view.Menu;  
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {  
EditText editfirstname;
EditText editlastname;
EditText editamount;
String firstname , lastname , amount;
Button button;
@Override  
protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.activity_main);  
    editfirstname= (EditText) findViewById(R.id.editfirstname);
    editlastname= (EditText) findViewById(R.id.editlastname);
    editamount = (EditText) findViewById(R.id.editamount);
    button = (Button) findViewById(R.id.submitbutton);



    final DatabaseHandler db = new DatabaseHandler(this); 
    button.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
             firstname = editfirstname.getText().toString();
                lastname = editlastname.getText().toString();
                amount = editamount.getText().toString();
             db.addContact(new Contact(firstname,lastname,amount));
             Log.d("Inserted" , " Inserted successfully");

        }
    });


    // Reading all contacts  
    Log.d("Reading: ", "Reading all contacts..");  
    List<Contact> contacts = db.getAllContacts();         

    for (Contact cn : contacts) {  
     String log = "Id: "+cn.getID()+" ,First Name: " + cn.getfName() +", Last Name: " + cn.getlName() + " ,Amount: " +   
        cn.getAmount();  
    // Writing Contacts to log  
    Log.d("Name: ", log);  
}  
}  

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

} 

activity_main.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"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/labelfirstname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Enter Firstname"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
    android:id="@+id/editfirstname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView1"
    android:layout_weight="1"
    android:ems="10" >

    <requestFocus />
</EditText>

<TextView
    android:id="@+id/labellastname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/editText1"
    android:layout_marginTop="23dp"
    android:text="Enter Lastname"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
    android:id="@+id/editlastname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView2"
    android:layout_marginTop="17dp"
    android:ems="10" />

<TextView
    android:id="@+id/labelamount"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/editText2"
    android:layout_marginTop="29dp"
    android:text="Enter Amount"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
    android:id="@+id/editamount"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:ems="10" />

<Button
    android:id="@+id/submitbutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/editText3"
    android:layout_marginTop="37dp"
    android:text="Submit" />

</RelativeLayout>

logcat的

02-04 18:47:37.553: E/AndroidRuntime(859): FATAL EXCEPTION: main
02-04 18:47:37.553: E/AndroidRuntime(859): java.lang.RuntimeException: Expecting menu, got RelativeLayout
02-04 18:47:37.553: E/AndroidRuntime(859):  at android.view.MenuInflater.parseMenu(MenuInflater.java:143)
02-04 18:47:37.553: E/AndroidRuntime(859):  at android.view.MenuInflater.inflate(MenuInflater.java:110)
02-04 18:47:37.553: E/AndroidRuntime(859):  at com.example.databaseex.MainActivity.onCreateOptionsMenu(MainActivity.java:59)
02-04 18:47:37.553: E/AndroidRuntime(859):  at android.app.Activity.onCreatePanelMenu(Activity.java:2490)
02-04 18:47:37.553: E/AndroidRuntime(859):  at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:407)
02-04 18:47:37.553: E/AndroidRuntime(859):  at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:769)
02-04 18:47:37.553: E/AndroidRuntime(859):  at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:201)
02-04 18:47:37.553: E/AndroidRuntime(859):  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749) 
02-04 18:47:37.553: E/AndroidRuntime(859):  at android.view.Choreographer.doCallbacks(Choreographer.java:562)
02-04 18:47:37.553: E/AndroidRuntime(859):  at android.view.Choreographer.doFrame(Choreographer.java:531)
02-04 18:47:37.553: E/AndroidRuntime(859):  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
02-04 18:47:37.553: E/AndroidRuntime(859):  at android.os.Handler.handleCallback(Handler.java:725)
02-04 18:47:37.553: E/AndroidRuntime(859):  at android.os.Handler.dispatchMessage(Handler.java:92)
02-04 18:47:37.553: E/AndroidRuntime(859):  at android.os.Looper.loop(Looper.java:137)
02-04 18:47:37.553: E/AndroidRuntime(859):  at android.app.ActivityThread.main(ActivityThread.java:5039)
02-04 18:47:37.553: E/AndroidRuntime(859):  at java.lang.reflect.Method.invokeNative(Native Method)
02-04 18:47:37.553: E/AndroidRuntime(859):  at java.lang.reflect.Method.invoke(Method.java:511)
02-04 18:47:37.553: E/AndroidRuntime(859):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-04 18:47:37.553: E/AndroidRuntime(859):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-04 18:47:37.553: E/AndroidRuntime(859):  at dalvik.system.NativeStart.main(Native Method)

请帮我解决问题

1 个答案:

答案 0 :(得分:1)

问题是您正在试图给布局"R.layout.activity_main"充气。

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

而不是onCreateOptionsMenu()方法上的菜单,例如:

getMenuInflater().inflate(R.menu.mymenu, menu);

菜单.xml文件必须存储在项目的/ res / menu文件夹中。

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/new_game"/>
    <item android:id="@+id/help"/>
</menu>

更多信息:

Android Menu

Android onCreateOptionsMenu()