我正在开发一个实现数据库的程序,以便添加联系人(电话号码联系人)。我似乎陷入了早期阶段的错误消息“无法解析方法addViewById(int)”
我之前已经编写了5个其他程序,之前已经多次使用addViewById按钮点击等。不确定我在这里缺少什么(但我确定在有人指出它之后会很明显lol)< / p>
这是我的代码:
爪哇: package 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" />
答案 0 :(得分:0)
也许你不需要这个按钮来插入消息,你可以创建一个类 MyHelper extends SQLiteOpenHelper ,Button和插入函数应该在<强> MainActivity 下,see here
答案 1 :(得分:0)
SQLiteOpenHelper
不是Activity
,它没有findViewById()
方法。你可能错了。
addNumber = (Button) this.findViewById(R.id.addNumberBtn);