Error in database (android studio) sql

1

table products has no column named direc 10-08 14: 25: 09.403 939-939 / com.example.arturosv.problem E / SQLiteDatabase: Error inserting Number = 6.0 direc = gh Tel = 67.0 name = a

Main main code

package com.example.arturosv.problem;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {
    // declaración de variables
    private EditText númeroCliente,nombreCliente,Telefono,Direccion;

    // Database Handler
    private DB BaseDatos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Asignación de variables
        númeroCliente = (EditText) findViewById(R.id.númeroCliente);
        nombreCliente = (EditText) findViewById(R.id.nombreCliente);
        Telefono = (EditText) findViewById(R.id.Telefono);
        Direccion= (EditText) findViewById(R.id.Direccion);

        // Instancia del objeto DB Handler
        BaseDatos = new DB (this, null, null, 1);
    }
    public void addProduct(View v){
        String name = nombreCliente.getText().toString();
        double numero = Double.parseDouble(númeroCliente.getText().toString());
        double telefono = Double.parseDouble(Telefono.getText().toString());
        String direccion=Direccion.getText().toString();

        Datos dato = new Datos (numero,direccion,telefono,name);

        BaseDatos.addProduct(dato);
        númeroCliente.setText("");
        nombreCliente.setText("");
        Telefono.setText("");
        Direccion.setText("");
        Toast.makeText(this, "Se añadió un nuevo dato",Toast.LENGTH_LONG).show();
        Log.d("Duplou", "Se añadió un producto");
    }

    public void findProduct(View v){
        String name = nombreCliente.getText().toString();

        Datos dato = BaseDatos.findProduct(name);

        if(dato == null){
            Toast.makeText(this, "No se encontró el producto",Toast.LENGTH_LONG).show();
            Log.d("Duplou", "No se encontró el producto");
        }else{
            nombreCliente.setText(dato.getName());
            númeroCliente.setText(Double.toString(dato.getNúmero()));
            Telefono.setText(Double.toString(dato.getTel()));
            Direccion.setText(dato.getDirec());
           Log.d("Duplou", "Id: " + dato.getId() + " - Nombre: " + dato.getName() + " - Precio: " + dato.getNúmero()+ "telefono: " + dato.getTel());
        }
    }

    public void deleteProduct(View v){
        String name = nombreCliente.getText().toString();

        boolean productoBorrado = BaseDatos.deleteProduct(name);

        if(productoBorrado){
            nombreCliente.setText("");
            númeroCliente.setText("");
            Telefono.setText("");
            Direccion.setText("");
            Log.d("Duplou", "Se borró el producto");
        }else{
            Log.d("Duplou", "El producto que se intentó borrar no existe");
        }

    }
}

DB.java code (here I create my base)

package com.example.arturosv.problem;

import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper;

public class DB extends SQLiteOpenHelper {

public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "DB.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_Numero = "Numero";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_TELEFONO = "Tel";
public static final String COLUMN_DIRECCION="direc";

public DB (Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION); // Crea la BD
}
@Override
public void onCreate(SQLiteDatabase db) {
    // Query para crear la tabla de productos
    String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_PRODUCTS  + " ("+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COLUMN_Numero + " DOUBLE," + COLUMN_NAME + " TEXT,"+ COLUMN_TELEFONO + " DOUBLE, "+ COLUMN_DIRECCION + " TEXT )";

    db.execSQL(CREATE_PRODUCTS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCTS);

    onCreate(db);
}
// Función para añadir un producto nuevo a la BD
public void addProduct(Datos dato){
    // Contenedor de valores para la base de datos
    ContentValues values = new ContentValues();

    // Configuramos lo valores del contenedor
    values.put(COLUMN_Numero, dato.getNúmero());
    values.put(COLUMN_NAME, dato.getName());
    values.put(COLUMN_TELEFONO, dato.getTel());
    values.put(COLUMN_DIRECCION, dato.getDirec());

    // Obtenemos el objeto de la base de datos escribible
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();

    // Insertamos el objeto en la BD
    sqLiteDatabase.insert(TABLE_PRODUCTS, null, values);
}
// Función para encontrar producto
public Datos findProduct(String name){

    // Hacemos el query
    String findQuery =
            "SELECT * FROM " +
                    TABLE_PRODUCTS  +
                    " WHERE " + COLUMN_NAME +
                    " = " + "\"" + name + "\"";

    // Obtenemos el objeto de la base de datos escribible
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();

    // Objeto que almacena el resultado
    Cursor cursor = sqLiteDatabase.rawQuery(findQuery,null);

    // Creamos un objeto de tipo producto
    Datos dato = new Datos ();

    // Checamos si existe un resultado de la búsqueda
    if(cursor.moveToFirst()){
        dato.setId(Integer.parseInt(cursor.getString(0)));
        dato.setNúmero(Double.parseDouble(cursor.getString(1)));
        dato.setName(cursor.getString(2));
        dato.setTel(Double.parseDouble(cursor.getString(3)));
        dato.setDirec(cursor.getString(4));;
    }else{
        dato = null;
    }

    cursor.close();

    return dato;
}

// Función para borrar un elemento
public boolean deleteProduct(String name){
    boolean deleted = false; // inicializamos la bandera de "borrado"

    // Se hace el query para buscar el objeto
    String findQuery =
            "SELECT * FROM " + TABLE_PRODUCTS +
                    " WHERE " + COLUMN_NAME + " = " +
                    "\"" + name + "\"";

    // Obtenemos el objeto de la base de datos escribible
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();

    // Objeto que almacena el resultado
    Cursor cursor = sqLiteDatabase.rawQuery(findQuery, null);

    if(cursor.moveToFirst()){
        String deleteQuery =
                "DELETE FROM " + TABLE_PRODUCTS +
                        " WHERE " + COLUMN_NAME + " = " +
                        "\"" + name + "\"";

        sqLiteDatabase.execSQL(deleteQuery); // se ejecuta el query

        cursor.close(); // finaliza el uso del cursor

        deleted = true;
    }

    return deleted;
}

}

3.-Datos.java (the constructures)

package com.example.arturosv.problem;

/**
 * Created by ArturoSV on 08/10/2016.
 */
public class Datos {
    // Propiedades de un producto
    private int _id;
    private double _número;
    private String _name;
    private double _Tel;
    private String _direc;
    // Constructor simple
    public Datos() {
    }
    // Constructor nombre y precio

    //numero,direccion,telefono,name
    public Datos(double número, String direc, double Tel,String name) {
        this._número = número;
        this._name = name;
        this._Tel = Tel;
        this._direc=direc;
    }
    // Constructor con todos los parámetros
    public Datos (int id,double número, String direc, double Tel,String name) {
        this._id = id;
        this._número = número;
        this._name = name;
        this._Tel = Tel;
        this._direc=direc;
    }
    public int getId() {
        return _id;
    }
    public void setId(int id) {
        this._id = id;
    }
    public double getNúmero() {
        return _número;
    }
    public void setNúmero(double número) {
        this._número = número;
    }
    public String getName() {
        return _name;
    }
    public void setName(String name) {
        this._name = name;
    }
    public double getTel() {
        return _Tel;
    }
    public void setTel(double Tel) {
        this._Tel = Tel;
    }

    public String getDirec() {
        return _direc;
    }

    public void setDirec(String direc) {
        this._direc = direc;
    }
}
    
asked by Arturo Vera 08.10.2016 в 21:30
source

2 answers

0

I suggest you if you are trying it in the emulator to go to data-data and delete the bd created by the app and try again.

    
answered by 09.10.2016 / 13:55
source
2

The problem is specified in:

  

table products has no column named direc

Review the creation of your table productos does not contain a column named direc .

I see that your query creates the specified field.

public void onCreate(SQLiteDatabase db) { 
            // Query para crear la tabla de productos 
        String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + " ("+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_Numero + " DOUBLE," + COLUMN_NAME + " TEXT,"+ COLUMN_TELEFONO + " DOUBLE, "+ COLUMN_DIRECCION + " TEXT )";
     db.execSQL(CREATE_PRODUCTS_TABLE); 
}

Surely it was created incorrectly in some previous test.

Remove the application and try again, since this would be called the onCreate() method, which would again create the correct structure of your table.

    
answered by 08.10.2016 в 21:59