Alanagh
Alanagh

Reputation: 234

Using methods of classes in android programming

Hi everyone I am a beginner in android, please help. I have DBAdapter class which has different methods to manipulate my db. I want to call the method i.e. insert when button is clicked. However it only works outside of listener (View.OnClickListener).

    package com.dbclass;

    import android.app.Activity;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    public class DBActivity extends Activity {
        /** Called when the activity is first created. */
       @Override
       public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn1 = (Button)findViewById(R.id.Button01);
        btn1.setOnClickListener(btn1Listener);


        DBAdapter db = new DBAdapter(this);        
        db.open();  

        long id;
         // this needs to go to setOnclick method
        id = db.insertTitle(
                "0470285818",
                "Alanel",
                "Wrox");        

        Cursor c = db.getAllTitles();
        if (c.moveToFirst())
        {
            do {          
                DisplayTitle(c);
            } while (c.moveToNext());
        }
        db.close();
    }

    public void DisplayTitle(Cursor c)
    {
        Toast.makeText(this, 
                "id: " + c.getString(0) + "\n" +
                "ISBN: " + c.getString(1) + "\n" +
                "TITLE: " + c.getString(2) + "\n" +
                "PUBLISHER:  " + c.getString(3),
                Toast.LENGTH_LONG).show();        
    }
    private View.OnClickListener btn1Listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                 // db.insertTitle("0470285818", "Alanel", "Wrox");  

        }
    };
}

Upvotes: 0

Views: 398

Answers (3)

Matt
Matt

Reputation: 2189

It looks like you are closing db at the end of your onCreate() method. You should make sure to open() and close() it again in your onClick(). You should also probably do the actual work in a background thread that you start from you onClick() method.

Upvotes: 2

Will Tate
Will Tate

Reputation: 33509

The scope of db is only within your onCreate() method. You may want to make it a public member of your Class.

Upvotes: 0

Robby Pond
Robby Pond

Reputation: 73484

Make your db variable a field of the DBActivity. You probably don't want to do db operations on the UI thread though.

Upvotes: 2

Related Questions