gpt4 book ai didi

java - 在android编程中使用类的方法

转载 作者:行者123 更新时间:2023-12-01 19:18:51 27 4
gpt4 key购买 nike

大家好,我是android初学者,请帮忙。我有 DBAdapter 类,它有不同的方法来操作我的数据库。我想调用该方法,即单击按钮时插入。但是它只能在监听器 (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");

}
};
}

最佳答案

将您的 db 变量设置为 DBActivity 的字段。不过,您可能不想在 UI 线程上执行数据库操作。

关于java - 在android编程中使用类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5353094/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com