我知道有很多关于这个问题的线索,但我自己的问题都没有。 我在数据库中连接了一个微调器,显示特定表的外键。并且似乎插入错误。
02-18 11:44:34.500: E/SQLiteDatabase(20811): 错误插入 ConsumerName=android.database.sqlite.SQLiteCursor@4144fa58 kWh=801.0 _id=65324 Date=2013 -2-18 Previous= 98 当前=899
02-18 11:44:34.500: E/SQLiteDatabase(20811): android.database.sqlite.SQLiteConstraintException: 错误代码 19: 约束失败
public class ElectricMeterReader extends Activity {
private long rowID;
private EditText meterNoEt;
private EditText currentEt;
private EditText previousEt;
private EditText kWhEt;
private TextView dateTv;
private Spinner spinner;
private int mSpinnerSpeciesId;
private ElectricMeterReader mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.electric_meter_reader);
Bundle extras = getIntent().getExtras();
// rowID = extras.getLong(ConsumerList.ROW_ID);
dateTv = (TextView) findViewById(R.id.dateEmr);
meterNoEt = (EditText) findViewById(R.id.meterNumberEmr);
currentEt = (EditText) findViewById(R.id.currentReadingEmr);
previousEt = (EditText) findViewById(R.id.passReadingEmr);
kWhEt = (EditText) findViewById(R.id.kwhEmr);
spinner = (Spinner) findViewById(R.id.spinner);
// Loading spinner data from database
SQLiteDatabase db = new DatabaseOpenHelper(this).getWritableDatabase();
// Spinner Drop down elements
// List<String> lables = db.getAllLabels();
Cursor c = db.rawQuery(
"SELECT AccountID AS _id, ConsumerName FROM Consumers", null);
// Creating adapter for spinner
startManagingCursor(c);
String[] from = new String[] { "_id" };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter dataAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, c, from, to);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
// set spinner listener to display the selected item id
mContext = this;
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// On selecting a spinner item
//String label = parent.getItemAtPosition(position).toString();
Cursor c = (Cursor) parent.getItemAtPosition(position);
mSpinnerSpeciesId = c.getInt(c
.getColumnIndexOrThrow("ConsumerName"));
// Showing selected spinner item
/* Toast.makeText(parent.getContext(), "You selected: " + label,
Toast.LENGTH_LONG).show();*/
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
final Calendar ca = Calendar.getInstance();
int yy = ca.get(Calendar.YEAR);
int mm = ca.get(Calendar.MONTH);
int dd = ca.get(Calendar.DAY_OF_MONTH);
dateTv.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(yy).append(" ").append("-").append(mm + 1).append("-")
.append(dd));
if (extras != null) {
rowID = extras.getLong("_id");
// meterNoEt.setText(extras.getString("MeterNumber"));
// set current date into textview
// Spinner click listener
currentEt.setText(extras.getString("Current"));
previousEt.setText(extras.getString("Previous"));
kWhEt.setText(extras.getString("kWh"));
// dateTv.setText(extras.getString("Date"));
}
Button calButton = (Button) findViewById(R.id.calculateDef);
calButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
float result = Float.parseFloat(currentEt.getText().toString())
- Float.parseFloat(previousEt.getText().toString());
kWhEt.setText(Float.toString(result));
}
});
Button saveButton = (Button) findViewById(R.id.addConsumption);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (kWhEt.getText().length() != 0) {
AsyncTask<Object, Object, Object> saveContactTask = new AsyncTask<Object, Object, Object>() {
@Override
protected Object doInBackground(Object... params) {
saveContact();
return null;
}
@Override
protected void onPostExecute(Object result) {
/*
* Intent addContact = new Intent(
* ElectricMeterReader.this,
* ConsumerReadList.class);
* startActivity(addContact);
*/
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else {
AlertDialog.Builder alert = new AlertDialog.Builder(
ElectricMeterReader.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.consumer_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addConsumerItem:
Intent addContact = new Intent(ElectricMeterReader.this,
AddEditConsumer.class);
startActivity(addContact);
return true;
case R.id.consumerInfo:
Intent electricMeterReader = new Intent(ElectricMeterReader.this,
ViewConsumer.class);
startActivity(electricMeterReader);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void saveContact() {
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null) {
dbConnector.insertConsumption(meterNoEt.getText().toString(),
currentEt.getText().toString(), previousEt.getText()
.toString(), kWhEt.getText().toString(), dateTv
.getText().toString(),
spinner.getItemAtPosition(mSpinnerSpeciesId).toString()
);
} else {
dbConnector.updateConsumption(rowID,
currentEt.getText().toString(), previousEt.getText()
.toString(), kWhEt.getText().toString(), dateTv
.getText().toString(),
spinner.getItemAtPosition(mSpinnerSpeciesId).toString());
}
}
将编码的方法插入到我的数据库连接器中
public void insertConsumption(String meter_number, String current,
String previous, String kWh, String date, String consumer_name) {
ContentValues newCons = new ContentValues();
newCons.put("_id", meter_number);
newCons.put("Current", current);
newCons.put("Previous", previous);
newCons.put("kWh", kWh);
newCons.put("Date", date);
newCons.put("ConsumerName", consumer_name);
open();
database.insert("Consumptions", null, newCons);
close();
}
我的数据库Openhelper
public class DatabaseOpenHelper extends SQLiteOpenHelper {
static final String dbName = "ElectricMeterDB";
static final String tableLabels = "labels";
static final String consumptionsTable = "Consumptions";
static final String colMeterNumber = "_id";
static final String colCurrent = "Current";
static final String colPrevious = "Previous";
static final String colkWh = "kWh";
static final String colDate = "Date";
static final String colConsumer = "ConsumerName";
static final String consumersTable = "Consumers";
static final String colAccountID = "AccountID";
static final String colName = "ConsumerName";
static final String colAddress = "Address";
public static final String viewReads = "ViewReading";
public DatabaseOpenHelper(Context context) {
super(context, dbName, null, 2);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + consumersTable + " (" + colAccountID
+ " INTEGER PRIMARY KEY NOT NULL," + colName + " TEXT NOT NULL, "
+ colAddress + " TEXT NOT NULL);");
db.execSQL("CREATE TABLE " + consumptionsTable + " (" + colMeterNumber
+ " INTEGER PRIMARY KEY NOT NULL," + colCurrent + " INTEGER, "
+ colPrevious + " INTEGER, " + colkWh + " INTEGER, " + colDate
+ " TEXT, " + colConsumer + " INTEGER NOT NULL, FOREIGN KEY ("
+ colConsumer + ") REFERENCES " + consumersTable + " ("
+ colAccountID + "));");
db.execSQL("CREATE TRIGGER fk_cmpcons_consid" + " BEFORE INSERT "
+ " ON " + consumptionsTable + " FOR EACH ROW BEGIN"
+ " SELECT CASE WHEN ((SELECT " + colAccountID + " FROM "
+ consumersTable + " WHERE " + colAccountID + " =new."
+ colConsumer + ") IS NULL)"
+ "THEN RAISE (ABORT, 'Foreign Key Violation') END;" + "END;");
db.execSQL("CREATE VIEW " + viewReads + " AS SELECT "
+ consumptionsTable + " . " + colMeterNumber + " AS _id, "
+ consumptionsTable + " . " + colCurrent + " ,"
+ consumptionsTable + " . " + colPrevious + " ,"
+ consumptionsTable + " . " + colkWh + ", " + consumptionsTable
+ " . " + colDate + "," + consumersTable + "." + colConsumer
+ " FROM " + consumptionsTable + " JOIN " + consumersTable
+ " ON " + consumptionsTable + " . " + colConsumer + " = "
+ consumersTable + "." + colAccountID);
// Inserts pre-defined consumers
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + consumptionsTable);
db.execSQL("DROP TABLE IF EXISTS" + consumersTable);
db.execSQL("DROP TRIGGER IF EXISTS consumers_id_trigger");
db.execSQL("DROP TRIGGER IF EXISTS consumers_id_trigger22");
db.execSQL("DROP TRIGGER IF EXISTS fk_cmpcons_consid");
db.execSQL("DROP VIEW IF EXISTS" + viewReads);
onCreate(db);
}
public void insertLabel(String label) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(colName, label);
// Inserting Row
db.insert(tableLabels, null, values);
db.close(); // Closing database connection
}
/**
* Getting all labels returns list of labels
* */
public List<String> getAllLabels() {
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + consumersTable;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
}
我被这个问题困住了。请帮我。感谢 future 的回应。
日志.d
02-18 13:49:59.870: D/saveContact(30881): _id: 36698521 ConsumerName: android.database.sqlite.SQLiteCursor@4144f700
我的数组适配器;
public void arrayAdapterList() {
final String[] from = new String[] { DatabaseOpenHelper.colAccountID };
// int[] to = new int[] { android.R.id.text1 };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, from);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner = (Spinner) findViewById(R.id.spinner);
// attaching data adapter to spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// On selecting a spinner item
// String col= c.getString(c.getColumnIndex("_id"));
int item = spinner.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You Selected: " + from[item],
Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
}
最佳答案
似乎您插入的某些值对于 NOT NULL 字段(在您的情况下为 ConsumerName)或 PK(在您的情况下为 _id)已经存在。错误代码 19 表示在操作(INSERT 等)期间违反了表约束(NOT NULL、UNIQUE 等)。这是 SQLITE Error Codes 的列表
android.database.sqlite.SQLiteCursor@4144fa58 是分配给 ConsumerName 的垃圾值。因此,请采取一些解决方法,以便从游标中获取 ConsumerName 的正确 FK。
你的 SimpleCursorAdapter 有问题。所以请看一下。如果您在 spinner 中获得正确的值,那么请像这样 spinner.getSelectedItem().toString(); 而不是 spinner.getItemAtPosition(mSpinnerSpeciesId).toString().
希望对你有帮助。
关于android - 插入 android.database.sqlite.sqliteconstraintexception 错误代码 19 约束失败时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14929277/
我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po
如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby
在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has
我已经构建了一些serverspec代码来在多个主机上运行一组测试。问题是当任何测试失败时,测试会在当前主机停止。即使测试失败,我也希望它继续在所有主机上运行。Rakefile:namespace:specdotask:all=>hosts.map{|h|'spec:'+h.split('.')[0]}hosts.eachdo|host|begindesc"Runserverspecto#{host}"RSpec::Core::RakeTask.new(host)do|t|ENV['TARGET_HOST']=hostt.pattern="spec/cfengine3/*_spec.r
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
我的主要目标是能够完全理解我正在使用的库/gem。我尝试在Github上从头到尾阅读源代码,但这真的很难。我认为更有趣、更温和的踏脚石就是在使用时阅读每个库/gem方法的源代码。例如,我想知道RubyonRails中的redirect_to方法是如何工作的:如何查找redirect_to方法的源代码?我知道在pry中我可以执行类似show-methodmethod的操作,但我如何才能对Rails框架中的方法执行此操作?您对我如何更好地理解Gem及其API有什么建议吗?仅仅阅读源代码似乎真的很难,尤其是对于框架。谢谢! 最佳答案 Ru
我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的
几个月前,我读了一篇关于rubygem的博客文章,它可以通过阅读代码本身来确定编程语言。对于我的生活,我不记得博客或gem的名称。谷歌搜索“ruby编程语言猜测”及其变体也无济于事。有人碰巧知道相关gem的名称吗? 最佳答案 是这个吗:http://github.com/chrislo/sourceclassifier/tree/master 关于ruby-寻找通过阅读代码确定编程语言的rubygem?,我们在StackOverflow上找到一个类似的问题:
我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur