我正在开发实现数据库的程序,因此可以添加联系人(电话号码联系人)。错误消息“无法解析方法addViewById(int)”似乎使我陷入了早期阶段
在此之前,我已经编写了5个其他程序,并多次使用addViewById进行按钮单击等操作。不确定我在这里缺少什么(但是我敢肯定,在有人指出来之后,它会很明显)
这是我的代码:
Java:
软件包cornez.com.databaseassignment;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
public class MainActivity extends SQLiteOpenHelper {
/*public class EmergencyDbOpenHelper extends SQLiteOpenHelper
{
/**
* Construct a SQLiteOpenHelper object for the
* emergency database.
*/
Button addNumber;
public MainActivity(Context context)
{
super(context, EmergencyDbContract.DB_NAME, null,
EmergencyDbContract.DB_VERSION);
}
public void onCreate(SQLiteDatabase db)
{
String createSql =
"create table " + EmergencyDbContract.TABLE_NAME
+ "("
+ " _id integer primary key,"
+ " name text not null,"
+ " phone_num text not null"
+ ")";
db.execSQL(createSql);
addNumber = (Button) this.findViewById(R.id.addNumberBtn);
insertContacts(db);
}
我们可以在^^上方看到addNumber分配
这是其余的Java代码:
@Override
public void onUpgrade(SQLiteDatabase db,
int oldVersion, int newVersion)
{
// This is version 1 so no actions are required.
// Possible actions include dropping/recreating
// tables, saving/restoring data in tables, etc.
}
private void insertContacts(SQLiteDatabase db)
{
// perform inserts to initialize the database
/*String tableName = "emergency_contacts";
ContentValues values = new ContentValues();
values.put("name", "OSS Surf Report");
values.put("phone_num", "8436330268");
db.insert(tableName, null, values); */
String insertSql =
"insert into emergency_contacts"
+ " (name, phone_num) values"
+ " (\"OSS Surf Report\", \"8436330268\")";
db.execSQL(insertSql);
}
}
public final class EmergencyDbContract
{
public static final String DB_NAME = "emergency.db";
public static final int DB_VERSION = 1;
public static final String TABLE_NAME = "emergency_contacts";
public static final String[] COLUMNS
= { "_id", "name", "phone_num" };
public static final String AUTHORITY
= "edu.citadel.android.emergency";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_NAME);
private EmergencyDbContract() {} // prevent instantiation
}
该按钮的 XML 标记为:
android:id="@+id/addNumberBtn" />
最佳答案
也许您不需要此按钮来插入消息,您可以创建一个类 MyHelper 扩展了 SQLiteOpenHelper ,该按钮和插入函数应该位于 MainActivity ,see here中