0

I am trying to get three inputs from the user (firstname , lastname , amount).All the three are string . I want to insert it in SQLite database but its giving a runtime exception. Below is my code:

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)

Please help me to solve the issue

1 Answer 1

1

the problem is that you are tryin to inflate a layout "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;  
}  

instead of a menu on the onCreateOptionsMenu() method, for example:

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

the menu .xml files must be stored on the /res/menu folder of your project.

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

More info:

Android Menu

Android onCreateOptionsMenu()

Sign up to request clarification or add additional context in comments.

2 Comments

5 seconds faster (cu 5 secunde mai rapida ca mine) ... +1
The problem is not the insert is this line getMenuInflater().inflate(R.layout.activity_main, menu); you have to inflate a menu not a layout.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.