开发者

Using methods of classes in android programming

开发者 https://www.devze.com 2023-02-18 19:09 出处:网络
Hi everyone I am a beginner in android, please help. I have DBAdapter class which has different methods to manipulate my db.

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;
    impor开发者_开发问答t 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");  

        }
    };
}


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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消