表不包含外键列

时间:2016-05-28 09:21:13

标签: java android sqlite

我正在尝试创建一个名为Reminder的表,其中包含用户名作为名为User的表中的外键。但我得到表提醒在运行时没有名为Username 的列。

添加用户代码。

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();
}
}

1 个答案:

答案 0 :(得分:1)

让我猜一下,首先你在Reminder中没有Username列,并且你试图将它添加到表中?

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

您应该通过扩展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;
    }

}

在你的活动中使用这个 -

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

您应该快速查看android SQL Database documentation