tags:

views:

333

answers:

4

I am using 8 EditText boxes from the NewCard.xml from which i am taking the values and when the save button is pressed i am storing the values into a database, in the same process of saving i am trying to get the values and present them into 8 different TextView boxes on the main.xml file and when i press the button i get an FC from the emulator and the resulting error is java.lang.NullPointerException. If Some 1 could help me that would be great, since i have never used databases and this is my first application for android and this is the only thing keepeng me to complete the whole thing and publish it on the market like a free app. Here's the full code from NewCard.java.

public class NewCard extends Activity 
{
    private static String[] FROM = { _ID, FIRST_NAME, LAST_NAME, POSITION, POSTAL_ADDRESS, PHONE_NUMBER, FAX_NUMBER, MAIL_ADDRESS, WEB_ADDRESS};
    private static String ORDER_BY = FIRST_NAME;

    private CardsData cards;

    EditText First_Name;
    EditText Last_Name;
    EditText Position;
    EditText Postal_Address;
    EditText Phone_Number;
    EditText Fax_Number;
    EditText Mail_Address;
    EditText Web_Address;
    Button New_Cancel;
    Button New_Save;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newcard);

        cards = new CardsData(this);

        //Define the Cancel Button in NewCard Activity
        New_Cancel = (Button) this.findViewById(R.id.new_cancel_button);
            //Define the Cancel Button Activity/s
            New_Cancel.setOnClickListener
            (
                new OnClickListener()
                {
                    public void onClick(View arg0)
                    {
                        NewCancelDialog();
                    }
                }
            );//End of the Cancel Button Activity/s

        //Define the Save Button in NewCard Activity
        New_Save = (Button) this.findViewById(R.id.new_save_button);
        //Define the EditText Fields to Get Their Values Into the Database
        First_Name = (EditText) this.findViewById(R.id.new_first_name);
        Last_Name = (EditText) this.findViewById(R.id.new_last_name);
        Position = (EditText) this.findViewById(R.id.new_position);
        Postal_Address = (EditText) this.findViewById(R.id.new_postal_address);
        Phone_Number = (EditText) this.findViewById(R.id.new_phone_number);
        Fax_Number = (EditText) this.findViewById(R.id.new_fax_number);
        Mail_Address = (EditText) this.findViewById(R.id.new_mail_address);
        Web_Address = (EditText) this.findViewById(R.id.new_web_address);

            //Define the Save Button Activity/s
            New_Save.setOnClickListener
            (
                new OnClickListener()
                {
                    public void onClick(View arg0)
                    {
                        //Add Code For Saving The Attributes Into The Database
                        try
                        {
                            addCard(First_Name.getText().toString(), Last_Name.getText().toString(),
                                    Position.getText().toString(), Postal_Address.getText().toString(),
                                    Integer.parseInt(Phone_Number.getText().toString()), 
                                    Integer.parseInt(Fax_Number.getText().toString()),
                                    Mail_Address.getText().toString(), Web_Address.getText().toString());
                            Cursor cursor = getCard();
                            showCard(cursor);
                        }
                        finally
                        {
                            cards.close();
                            NewCard.this.finish();
                        }
                    }
                }
            );//End of the Save Button Activity/s
    }

    //======================================================================================//
    //DATABASE FUNCTIONS
    private void addCard(String firstname, String lastname, String position, String postaladdress,
                        int phonenumber, int faxnumber, String mailaddress, String webaddress)
    {
          // Insert a new record into the Events data source.
          // You would do something similar for delete and update.
        SQLiteDatabase db = cards.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(FIRST_NAME, firstname);
        values.put(LAST_NAME, lastname);
        values.put(POSITION, position);
        values.put(POSTAL_ADDRESS, postaladdress);
        values.put(PHONE_NUMBER, phonenumber);
        values.put(FAX_NUMBER, phonenumber);
        values.put(MAIL_ADDRESS, mailaddress);
        values.put(WEB_ADDRESS, webaddress);
        db.insertOrThrow(TABLE_NAME, null, values); 
    }

    private Cursor getCard()
    {
        // Perform a managed query. The Activity will handle closing
        // and re-querying the cursor when needed.
        SQLiteDatabase db = cards.getReadableDatabase();
        Cursor cursor = db.query(TABLE_NAME, FROM, null, null, null, null, ORDER_BY);
        startManagingCursor(cursor);
        return cursor;
    }

    private void showCard(Cursor cursor)
    {
        // Stuff them all into a big string
        long id = 0;
        String firstname = null;
        String lastname = null;
        String position = null; 
        String postaladdress = null;
        long phonenumber = 0;
        long faxnumber = 0; 
        String mailaddress = null;
        String webaddress = null;

        while (cursor.moveToNext())
        {
            // Could use getColumnIndexOrThrow() to get indexes
            id = cursor.getLong(0); 
            firstname = cursor.getString(1);
            lastname = cursor.getString(2);
            position = cursor.getString(3); 
            postaladdress = cursor.getString(4);
            phonenumber = cursor.getLong(5);
            faxnumber = cursor.getLong(6); 
            mailaddress = cursor.getString(7);
            webaddress = cursor.getString(8);
        }
        // Display on the screen add for each textView
        TextView ids = (TextView) findViewById(R.id.id); 
        TextView fn = (TextView) findViewById(R.id.firstname); 
        TextView ln = (TextView) findViewById(R.id.lastname); 
        TextView pos = (TextView) findViewById(R.id.position); 
        TextView pa = (TextView) findViewById(R.id.postaladdress); 
        TextView pn = (TextView) findViewById(R.id.phonenumber); 
        TextView fxn = (TextView) findViewById(R.id.faxnumber); 
        TextView ma = (TextView) findViewById(R.id.mailaddress); 
        TextView wa = (TextView) findViewById(R.id.webaddress); 

        ids.setText(String.valueOf(id)); //this is the line reported when i get the error
        fn.setText(String.valueOf(firstname));
        ln.setText(String.valueOf(lastname));
        pos.setText(String.valueOf(position)); 
        pa.setText(String.valueOf(postaladdress));
        pn.setText(String.valueOf(phonenumber));
        fxn.setText(String.valueOf(faxnumber)); 
        ma.setText(String.valueOf(mailaddress));
        wa.setText(String.valueOf(webaddress));
    }

    //======================================================================================//
    //Define the Dialog that alerts you when you press the Cancel button
    private void NewCancelDialog() 
    {
        new AlertDialog.Builder(this)
            .setMessage("Are you sure you want to cancel?")
            .setTitle("Cancel")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialog, int id) 
                        {
                            NewCard.this.finish();
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialog, int id)
                        {
                            dialog.cancel();
                        }
                    })
                    .show();
    }//End of the Cancel Dialog

}

Here is the error stack:

06-07 19:05:21.728: ERROR/AndroidRuntime(207): Uncaught handler: thread main exiting due to uncaught exception
06-07 19:05:21.788: ERROR/AndroidRuntime(207): java.lang.NullPointerException
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at com.test.android.bussinesscard.NewCard.showCard(NewCard.java:181)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at com.test.android.bussinesscard.NewCard.access$1(NewCard.java:143)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at com.test.android.bussinesscard.NewCard$2.onClick(NewCard.java:104)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at android.view.View.performClick(View.java:2364)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at android.view.View.onTouchEvent(View.java:4179)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at android.widget.TextView.onTouchEvent(TextView.java:6541)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at android.view.View.dispatchTouchEvent(View.java:3709)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at android.os.Looper.loop(Looper.java:123)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at android.app.ActivityThread.main(ActivityThread.java:4363)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at java.lang.reflect.Method.invokeNative(Native Method)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at java.lang.reflect.Method.invoke(Method.java:521)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
06-07 19:05:21.788: ERROR/AndroidRuntime(207):     at dalvik.system.NativeStart.main(Native Method)
A: 

Have you made sure that your id db field is auto-increment. Also perhaps try using cursor.moveToFirst() rather than moveToNext()

disretrospect
Yes the id db field is auto-increment, and for the cursor.moveToFirst() i'll try it now.
nCounTr
when i put cursor.moveToFirst() the emulator freezes.
nCounTr
Hmmm. It's worth wrapping your cursor.move to in an if(cursor.getCount() > 0) { // your code here } else { Log.d('NewCard', '0 rows found'); }
disretrospect
ok i pulled my database from the emulator and it has all rows and ll of the data put into it and its all correct no errors. So i am able to store data just fine with no errors but i'm getting errors when trying to get data from the database.
nCounTr
Ok some more things you could try: Get rid of your String.valueOf. Most of your variables are Strings anyway and for the Longs use Long.toString(). Also can you print out id using Log.d and see what it gives you in LogCat.
disretrospect
ok i'll get rid of the string.valueOf and will use Long.toString(). I'll try to print the id and see what gives me and will post here.
nCounTr
The log is not shown at all.
nCounTr
Are you using LogCat? Eclipse->Window->Show View->Other…->Android->LogCat
disretrospect
Yes im using it.
nCounTr
A: 

Your NullPointerException indicates that you have no TextView named @+id/id, possibly because that's not a really good value to use. Change it to some other name and see if that helps.

CommonsWare
I've change it, but it doesn't help it shows the same error.Is it possible that i am using it wrong? I mean my function is on NewCard, and im trying to display it on the main screen in my case BusinessCard.java
nCounTr
No, that is not going to work. `NewCard` is an `Activity`. `findViewById()` will allow you to update widgets on `NewCard`, not any other activity. `NewCard` cannot modify any other `Activity`.
CommonsWare
So is there a way i can do this from the main?i can use new card just to store data because it works, and when i press the save button, i need them somehow to show them on the main screen. So i guess there's a way i can do this in the main.
nCounTr
+1  A: 

Have you verified the cursor returned in getCard() is not null? This query could be returning null..

Also, I would not hard code the column indexes in the showCard() method. Instead, use:

firstName = cursor.getString(cursor.getColumnIndex(FIRST_NAME);
Ricardo Villamil
I haven't verified it, i'll do so. And thanks for the tip for the showCard() method.
nCounTr
I'am verifying that the cursor is not null.
nCounTr
What line exactly is throwing the exception, from your log, line 181, can you paste it?
Ricardo Villamil
It's this line: ids.setText(String.valueOf(id)); in the file attached above that was changed to: ids.setText(Long.toString(id));
nCounTr
OK, change the id of the textview to something else other than id. "id" is somewhat of a keyword for layouts, change it to cardid (or whatever) and then change it in your code and try again.
Ricardo Villamil
Doesn't work, still gives me the same error.ComonsWare said that i cannot use this method to change stuff into main activity from NewCard activity, maybe that is the problem. But i don't know how to implement it into the main activity. Is there an update method that i can use?
nCounTr
Ah, he's right then, if id is not in your NewCard Activity you can't access it here. You can call the main activity from newcard and pass the id of the newly added card through Intents, then load the new card from the DB in the main activity, not in new card (basically move showCard() to the main activity)
Ricardo Villamil
Ricardo, i've made the following changes:In MainActivity i call the NewCard Activity with this method:startActivityForResult(new Intent(this, NewCard.class), RESULT_CODE_CONSTANT);In which RESULT_CODE_CONSTANT is set to 0.Now in NewCard in the onClick method for the Save button i use this code:Cursor cursor = getCard();returnCard(cursor);
nCounTr
And in returnCard() method i use this code:Intent CardIntent = new Intent();long cardid = 0;while (cursor.moveToNext()) { cardid = cursor.getLong(cursor.getColumnIndex(_ID));} CardIntent.putExtra("CardID", Long.toString(cardid)); setResult(RESULT_CODE_CONSTANT, CardIntent);}So when i use this code i'm not getting the NullPointerException, but i have another problem.When i add new card it displays 1, when i add another card it still displays 1 not 2 or 3 or 4. So im guessing im doing something wrong in my code.
nCounTr
A: 

Thanks to all for your unselfish help, i'll try the suggestion of Ricardo which i think will help. I'll put the name of the application when i'll make it official and post it on Android Market, i expect that it would be in a week or so, because im occupied with my work, hobbies etc...

nCounTr
nCounTr