java - 表不包含外键列

标签 java android sqlite

我正在尝试创建一个名为 Reminder 的表,该表由名为 User 的表中的用户名作为外键组成。但我在运行时收到表提醒没有名为用户名的列错误。

添加用户代码。

package com.example.champ.remindme;
import android.app.AlertDialog;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SignUp extends AppCompatActivity {
EditText editUsername,editPassword,editEmail,editMobileNumber;
Button btnSignUpButton;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_up);
    editUsername = (EditText)findViewById(R.id.editUsername);
    editPassword = (EditText)findViewById(R.id.editPassword);
    editEmail = (EditText)findViewById(R.id.editEmail);
    editMobileNumber = (EditText)findViewById(R.id.editMobileNumber);
    btnSignUpButton = (Button)findViewById(R.id.btnSiginUpButton);
    db=openOrCreateDatabase("RemindMe", Context.MODE_PRIVATE, null);
    db.execSQL("create table IF NOT EXISTS User (Username TEXT PRIMARY KEY ,Password TEXT, Email TEXT, Contact_No INTEGER)");
}
public  void AddUser(View v){
    if(editUsername.length()==0||
            editPassword.length()==0||
            editEmail.length()==0||
            editMobileNumber.length()==0)
    {
        showMessage("Error", "Please enter all values");
        return;
    }
    db.execSQL("INSERT INTO User VALUES('"+editUsername.getText().toString()+"'," +
            "'"+editPassword.getText().toString()+ "'," +
            "'"+editEmail.getText().toString()+"',"+
            "'"+Integer.parseInt(editMobileNumber.getText().toString())+"');");

    showMessage("Success", "Record added");
}

public void showMessage(String title,String message)
{
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.show();
}
}

添加提醒代码。

 package com.example.champ.remindme;
 import android.Manifest;
 import android.app.AlertDialog.Builder;
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.database.sqlite.SQLiteDatabase;
 import android.location.Address;
 import android.location.Geocoder;
 import android.os.Bundle;
 import android.support.v4.app.ActivityCompat;
 import android.support.v4.app.FragmentActivity;
 import android.view.View;
 import android.widget.EditText;
 import com.google.android.gms.maps.CameraUpdateFactory;
 import com.google.android.gms.maps.GoogleMap;
 import com.google.android.gms.maps.OnMapReadyCallback;
 import com.google.android.gms.maps.SupportMapFragment;
 import com.google.android.gms.maps.model.LatLng;
 import com.google.android.gms.maps.model.MarkerOptions;
 import java.io.IOException;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import java.util.List;

 public class AddEventPlace extends FragmentActivity implements  OnMapReadyCallback {

private GoogleMap mMap;
Double Latitude=0.0;
Double Longitude=0.0;
EditText edtAddress;
String username,item;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_event_place);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    edtAddress=(EditText)findViewById(R.id.Address);
    db=openOrCreateDatabase("RemindMe", Context.MODE_PRIVATE, null);
    db.execSQL("create table IF NOT EXISTS Reminder (" +
            "ID INTEGER PRIMARY KEY   AUTOINCREMENT," +
            "item TEXT not NULL," +
            "Time TIMESTAMP DEFAULT CURRENT_TIMESTAMP not NULL," +
            "Date DATETIME DEFAULT CURRENT_TIMESTAMP not NULL," +
            "x_coordinates REAL," +
            "y_coordinates  REAL," +
            "Username  TEXT," +
            "FOREIGN KEY(Username) REFERENCES User(Username));");
}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mMap.setMyLocationEnabled(true);
}


public void onSearch(View view)
{
    EditText location_tf = (EditText)findViewById(R.id.Address);
    String location = location_tf.getText().toString();
    List<Address> addressList = null;
    if(location != null || !location.equals(""))
    {
        Geocoder geocoder = new Geocoder(this);
        try {
            addressList = geocoder.getFromLocationName(location , 1);


        } catch (IOException e) {
            e.printStackTrace();
        }

        Address address = addressList.get(0);
        LatLng latLng = new LatLng(address.getLatitude() , address.getLongitude());
        Latitude=address.getLatitude();
        Longitude=address.getLongitude();
        //Latitude=0.0;
        //Longitude=0.0;
        mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
        mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

    }
}

 public  void Done(View view){
     username = getIntent().getStringExtra("Username");
     item = getIntent().getStringExtra("item");

     DateFormat timeFormat = new SimpleDateFormat("h:mm a");
     String time = timeFormat.format(Calendar.getInstance().getTime());
     DateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yy");
     String date = dateFormat.format(Calendar.getInstance().getTime());
     if(item.trim().length()==0||
             date.trim().length()==0||
             Longitude ==0.0||
             Latitude==0.0||
             username.trim().length()==0)
     {
         showMessage("Error", "Please enter all values");
         return;
     }
     db.execSQL("INSERT INTO Reminder (item, Time, Date, x_coordinates, y_coordinates, Username) VALUES(" +
             "'"+item+"'," +
             "'"+time+"'," +
             "'"+date+"',"+
             "'"+Longitude+"',"+
             "'"+Latitude+"',"+
             "'"+username+"'"+
             ");");

     showMessage("Success", "Record added");
 }

public void showMessage(String title,String message)
{
    Builder builder=new Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.show();
}
}

最佳答案

让我猜猜,首先您的提醒中没有“用户名”列,而您正尝试将其添加到表中?

问题可能是由于以前版本的代码而已经创建了没有用户名列的表,并且无法重新创建该表,因为它已经存在。

您应该通过扩展SQLiteOpenHelper来创建DBHelper,然后重写onUpgrade方法

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

    }

更多代码可以帮助您 -

public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "dpname.db";
    public static final String TABLE_NAME = "table1";
    public static final String COL1 = "col1";
    // More columns and tables ....
    private static final int DATABASE_VERSION = 2;
    //You should update database_version everytime you are trying to update the database, Note - data saved will be lost
    private static DBHelper mDbHelper;
    public void onCreate(SQLiteDatabase db) {
        String CREATE_FIRST_TABLE = "CREATE TABLE " + TABLE_NAME +
                "(" +
                COL1 + " INTEGER PRIMARY KEY ," +
                COL2 + " TEXT," +
                //... More columns
                ")";
        db.execSQL(CREATE_FIRST_TABLE);
        //.. Create More tables
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);

    }
    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    private DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // More functions to select, insert, delete, update records
    // Example a function to insert Post given below
    // Better make a class to hold your data structure for different tables

    public void insertDetail(String s1, String s2, Integer i1...){
         SQLiteDatabase db = this.getWritableDatabase();
         db.beginTransaction();   
         try {
               ContentValues values = new ContentValues();
               values.put(COL1,i1);
               values.put(COL2,s1);
               //....
               db.insertOrThrow(TABLE_NAME, null, values);
               db.setTransactionSuccessful();
         } catch(SQLException e){
               //....
         } finally{
               db.endTransaction();
         }          
    }

    public static synchronized DBHelper getInstance(Context context) {
       // Use the application context, which will ensure that you
       // don't accidentally leak an Activity's context.

       if (mDbHelper == null) {
           mDbHelper = new DBHelper(context.getApplicationContext());
       }
       return mDbHelper;
    }

}

在您的 Activity 中像这样使用它 -

db = DBHelper.getInstance(getApplicationContext());
db.insertDetail(String1,String2,Integer1);

您应该快速浏览一下 android SQL Database documentation

关于java - 表不包含外键列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37497305/

相关文章:

Java 循环错误 - 需要新的眼光

java - Clojure 宏实例化异常

java - 使用 JSON 执行 POST 时出现奇怪的 ExecutionException

android - 在here-api android中获取特定路线的到达/旅行时间

asp.net - SQLite更新查询参数不接受系统字符串值

sqlite - SQLite如果一个结果为空,如何选择另一行

sqlite - 你知道什么 SQLite 可视化开发工具吗?

java - 为什么 println() 方法被执行两次而不是一次?

java - Eclipse Mars DDMS 仅显示 Level 中的第一个字母,没有消息

java - 类 Activity 扩展了 ActionBarActivity 已弃用