0

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");  

        }
    };
}

3 Answers 3

2

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

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

Comments

2

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.

Comments

0

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

Comments

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.