我有一个问题,就是我正在做一个基于数据库存储地址ip和ip的记录的程序。 我在数据库中有两个表,一个名为automata,它存储IP地址(密钥),公司名称以及要放置IP地址的名称。
另一个表称为记录,并使用ip自动机将地址记录(密钥),这些名称,记录类型和外键保存到此relaccionada id_ip表中。
源(SQLite):
public class AdminSQLiteOpenHelper extends SQLiteOpenHelper {
String CreaSqlAutomata = "CREATE TABLE automata (ip TEXT PRIMARY KEY, empresa TEXT, nombre TEXT)";
String CreaSqlRegistro = "CREATE TABLE registro (direccion INTEGER PRIMARY KEY, tipo TEXT, nombreAutomata TEXT, id_ip TEXT, FOREIGN KEY(id_ip) REFERENCES automata(ip))";
public AdminSQLiteOpenHelper(Context contexto, String nombre,CursorFactory factory, int version) {
super(contexto, nombre, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CreaSqlAutomata);
db.execSQL(CreaSqlRegistro);
db.execSQL("CREATE TRIGGER fk_autreg_autip " +
" BEFORE INSERT "+" ON registro FOR EACH ROW BEGIN"+ " SELECT CASE `WHEN ((SELECT ip FROM automata WHERE ip=new.id_ip ) IS NULL)"+`
" THEN RAISE (ABORT,'Foreign Key Violation') END;"+
" END;");
}
@Override
public void onUpgrade(SQLiteDatabase db, int versionAnte, int versionNue) {
db.execSQL("DROP TABLE IF EXISTS automata");
db.execSQL("DROP TABLE IF EXISTS registro");
db.execSQL("DROP TRIGGER IF EXISTS fk_autreg_autip");
//Se crea la nueva versión de la tabla
db.execSQL(CreaSqlAutomata);
db.execSQL(CreaSqlRegistro);
db.execSQL("CREATE TRIGGER fk_autreg_autip " +
" BEFORE INSERT "+" ON registro FOR EACH ROW BEGIN"+ "SELECT CASE WHEN ((SELECT ip FROM automata WHERE ip=new.id_ip ) IS NULL)"+
" THEN RAISE (ABORT,'Foreign Key Violation') END;"+
" END;");
}
public class automatas {
private String nombre;
private String ip;
private String empresa;
// Constructor de un objeto Contactos
public automatas( String nombre, String ip, String empresa) {
this.nombre = nombre;
this.empresa = empresa;
this.ip = ip;
}
// Recuperar/establecer Ip
public String getIP() {
return ip;
}
public void setIP(String ip) {
this.ip = ip;
}
// Recuperar/establecer NOMBRE
public String getNOMBRE() {
return nombre;
}
public void setNOMBRE(String nombre) {
this.nombre = nombre;
}
// Recuperar/establecer EMPRESA
public String getEMPRESA() {
return empresa;
}
public void setEMPRESA(String empresa) {
this.empresa = empresa;
}
}
}
我想要的是保留一个记录,其中使用微调器的跛脚自动机的IP地址并记录用户的地址插入问题是当我键入自动机的IP地址失败时,是不是很好识别并且不知道为什么....我很绝望!
public class guardar_registros extends Activity {
Spinner spinner1,spinner2;
EditText nombre,direccion;
Button boton;
String basededatos= "BDautomata.db";
String registro_ip,tipo_registro;
int i = 0,flag=0;
Cursor cur;
String[] lista_ip = new String [20];
ArrayAdapter <CharSequence> lista;
List<String> lista_contactos = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.guardar_registros);
spinner1=(Spinner) findViewById(R.id.spinnerTipoRegistro);
spinner2=(Spinner) findViewById(R.id.spinnerIP);
nombre = (EditText)findViewById(R.id.NombreRegistro);
direccion = (EditText)findViewById(R.id.dirRegistro);
boton = (Button)findViewById(R.id.btnGuardarRegistro);
lista = new ArrayAdapter <CharSequence> (this, android.R.layout.simple_spinner_item );
lista.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
lista.add("Entero");
lista.add("Real(1 decimal)");
lista.add("Real (2 decimales)");
lista.add("Binario");
spinner1.setAdapter(lista);
cur = obtenerIP();
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_spinner_item , cur, new String[]{"_id"}, new int[] { android.R.id.text1 },0);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(mAdapter);
spinner2.setOnItemSelectedListener(new SpinnerListener2());
spinner1.setOnItemSelectedListener(new SpinnerListener1());
}
public Cursor obtenerIP (){
AdminSQLiteOpenHelper automata= new AdminSQLiteOpenHelper(this, "BDautomata", null, 1);
SQLiteDatabase bd = automata.getReadableDatabase();
Cursor c = bd.rawQuery(" SELECT ip AS _id FROM automata ", null);
return c;
}
public void guardarRegistro(View v) {
AdminSQLiteOpenHelper automata= new AdminSQLiteOpenHelper(this, "BDautomata", null, 1);
SQLiteDatabase bd = automata.getWritableDatabase();
if (bd!=null){
String nombreRegistro = nombre.getText().toString();
String direccionR = direccion.getText().toString();
ContentValues cv = new ContentValues();
cv.put("id_ip", registro_ip);
cv.put("direccion", direccionR);
cv.put("nombreAutomata", nombreRegistro);
cv.put("tipo", tipo_registro);
bd.insert("registro", "direccion", cv);
Toast.makeText(this, "Se guardaron los datos del automata",Toast.LENGTH_SHORT).show();
//comprobamos que funciona
}else
Toast.makeText(this, "Error al crear la base de datos", Toast.LENGTH_SHORT).show();
}
// Listener para el spinner2 el cual tiene las ip de los automatas
public class SpinnerListener2 implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
registro_ip=parent.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView<?> parent) {
//para asegurar que el usuario selecciona una ip
//flag=0;
}
}
//Listener del Spinner1 el cuel contiene el tipo del registro.
public class SpinnerListener1 implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
tipo_registro=parent.getItemAtPosition(pos).toString();
//flag=1;
}
public void onNothingSelected(AdapterView<?> parent) {
//para asegurar que el usuario selecciona una ip//flag=0;
}
}
}
logcat:
09-24 09:56:42.707: E/SQLiteDatabase(9212): Error inserting nombreAutomata=asd id_ip=android.database.sqlite.SQLiteCursor@40dfbc68 direccion=123 tipo=Entero
09-24 09:56:42.707: E/SQLiteDatabase(9212): android.database.sqlite.SQLiteConstraintException: Foreign Key Violation (code 19)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:775)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at com.JR.scada.guardar_registros.guardarRegistro(guardar_registros.java:84)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at java.lang.reflect.Method.invokeNative(Native Method)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at java.lang.reflect.Method.invoke(Method.java:511)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at android.view.View$1.onClick(View.java:3594)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at android.view.View.performClick(View.java:4204)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at android.view.View$PerformClick.run(View.java:17355)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at android.os.Handler.handleCallback(Handler.java:725)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at android.os.Handler.dispatchMessage(Handler.java:92)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at android.os.Looper.loop(Looper.java:137)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at android.app.ActivityThread.main(ActivityThread.java:5041)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at java.lang.reflect.Method.invokeNative(Native Method)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at java.lang.reflect.Method.invoke(Method.java:511)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-24 09:56:42.707: E/SQLiteDatabase(9212): at dalvik.system.NativeStart.main(Native Method)
感谢您的关注。