在sqllite数据库上多次插入相同的数据

时间:2018-05-28 17:20:05

标签: java android sql sqlite crud

我试图在android开发工作室上创建一个简单的CRUD表单。

我可以将数据输入到数据库中,但它似乎只能选择“县”#39; texField。因此,每条记录都设置为县textField中的任何记录。我认为它可能与项目变量和声明有关,但我不知道什么是错的。 提前谢谢。

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainDatabase extends AppCompatActivity {

    private static final String TAG = "MainDatabase";

    DatabaseHelper mDatabaseHelper;
    private Button btnAdd, btnViewData;
    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = findViewById(R.id.editText);
        editText = findViewById(R.id.editTextLast);
        editText = findViewById(R.id.editPassword);
        editText = findViewById(R.id.editPasswordConfirm);
        editText = findViewById(R.id.editPhoneNumber);
        editText = findViewById(R.id.editEmailAddress);
        editText = findViewById(R.id.editAddressLine1);
        editText = findViewById(R.id.editAddressLine2);
        editText = findViewById(R.id.postcodeUser);
        editText = findViewById(R.id.county);
        btnAdd = findViewById(R.id.btnAdd);
        btnViewData = findViewById(R.id.btnView);
        mDatabaseHelper = new DatabaseHelper(this);

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newEntry = editText.getText().toString();
                String newName = editText.getText().toString();
                Integer newPass = Integer.parseInt(editText.getText().toString());
                String newPhone = editText.getText().toString();
                String newEmail = editText.getText().toString();
                String newAdd1 = editText.getText().toString();
                String newAdd2 = editText.getText().toString();
                String newPC = editText.getText().toString();
                String newCounty = editText.getText().toString();

                if (editText.length() != 0) {
                    AddData(newEntry, newName, newPass, newPhone, newEmail, newAdd1, newAdd2, newPC, newCounty);


                    editText.setText("");
                } else {
                    toastMessage("You must put something in the text field!");
                }

            }
        });

        btnViewData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainDatabase.this, ListDataActivity.class);
                startActivity(intent);
            }
        });

    }



    public void AddData(String newEntry, String newName, Integer newPass, String newPhone, String newEmail, String newAdd1, String newAdd2, String newPC, String newCounty) {
        boolean insertData = mDatabaseHelper.addData(newEntry,newName,newPass,newPhone,newEmail,newAdd1,newAdd2,newPC,newCounty);


        if (insertData) {
            toastMessage("Data Successfully Inserted!");
        } else {
            toastMessage("Something went wrong");
        }
    }

    /**
     * customizable toast
     * @param message
     */
    private void toastMessage(String message){
        Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
    }
}

数据库助手

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

/**
 * Created by User on 2/28/2017.
 */

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String TAG = "DatabaseHelper";

    private static final String TABLE_NAME = "people_table";
    private static final String COL1 = "ID";
    private static final String COL2 = "name";
    private static final String COL3 = "lastname";
    private static final String COL4 = "phonenumber";
    private static final String COL5 = "addressline1";
    private static final String COL6 = "addressline2";
    private static final String COL7 = "postcode";
    private static final String COL8 = "county";
    private static final String COL9 = "email";
    private static final String COL10 = "password";

    public DatabaseHelper(Context context) {
        super(context, TABLE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE " + TABLE_NAME + " (" + COL1 +  " INTEGER PRIMARY KEY AUTOINCREMENT," +
                COL2 +" TEXT," +
                COL3 +" TEXT," +
                COL4 +" INTEGER," +
                COL5 +" TEXT," +
                COL6 +" TEXT,"+
                COL7 +" TEXT,"+
                COL8 +" TEXT,"+
                COL9 +" TEXT,"+
                COL10 +" TEXT" + ")";
        db.execSQL(createTable);


    }

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

    public boolean addData(String item, String item2, Integer item3, String item4, String item5, String item6, String item7, String item8, String item9) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, item);
        contentValues.put(COL3, item2);
        contentValues.put(COL4, item3);
        contentValues.put(COL5, item4);
        contentValues.put(COL6, item5);
        contentValues.put(COL7, item6);
        contentValues.put(COL8, item7);
        contentValues.put(COL9, item8);
        contentValues.put(COL10, item9);


        Log.d(TAG, "addData: Adding " + item + item2 + item3 + item4 + item5 + item6 + item7 + item8 + item9 + " to " + TABLE_NAME);

        long result = db.insert(TABLE_NAME, null, contentValues);

        //if date as inserted incorrectly it will return -1
        if (result == -1) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Returns all the data from database
     * @return
     */
    public Cursor getData(){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_NAME;
        Cursor data = db.rawQuery(query, null);
        return data;
    }

    /**
     * Returns only the ID that matches the name passed in
     * @param name
     * @return
     */
    public Cursor getItemID(String name){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT " + COL1 + " FROM " + TABLE_NAME +
                " WHERE " + COL2 + " = '" + name + "'";
        Cursor data = db.rawQuery(query, null);
        return data;
    }

    /**
     * Updates the name field
     * @param newName
     * @param id
     * @param oldName
     */
    public void updateName(String newName, int id, String oldName){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "UPDATE " + TABLE_NAME + " SET " + COL2 +
                " = '" + newName + "' WHERE " + COL1 + " = '" + id + "'" +
                " AND " + COL2 + " = '" + oldName + "'";
        Log.d(TAG, "updateName: query: " + query);
        Log.d(TAG, "updateName: Setting name to " + newName);
        db.execSQL(query);
    }

    /**
     * Delete from database
     * @param id
     * @param name
     */
    public void deleteName(int id, String name){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "DELETE FROM " + TABLE_NAME + " WHERE "
                + COL1 + " = '" + id + "'" +
                " AND " + COL2 + " = '" + name + "'";
        Log.d(TAG, "deleteName: query: " + query);
        Log.d(TAG, "deleteName: Deleting " + name + " from database.");
        db.execSQL(query);
    }

}

查看

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ScrollView01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.unn.android.loginregister.MainDatabase">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/relativeLayout1">
        <EditTextFirst
            android:layout_marginTop="100dp"
            android:textAlignment="center"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:id="@+id/editText"
            android:inputType="text"
            android:text="Firstname" />
        <EditText
            android:layout_marginTop="150dp"
            android:textAlignment="center"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:id="@+id/editTextLast"
            android:inputType="text"
            android:text="LastName" />

        <EditText
            android:layout_marginTop="200dp"
            android:id="@+id/editPassword"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPassword"
            android:text="Password"  />

        <EditText
            android:layout_marginTop="250dp"
            android:id="@+id/editPasswordConfirm"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPassword"
            android:text="Confirm Password"/>

        <EditText
            android:layout_marginTop="300dp"
            android:id="@+id/editPhoneNumber"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="phone"
            android:text="Phone"/>

        <EditText
            android:layout_marginTop="350dp"
            android:id="@+id/editEmailAddress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textEmailAddress"
            android:text="Email"/>

        <EditText
            android:layout_marginTop="400dp"
            android:id="@+id/editAddressLine1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="text"
            android:text="Address Line 1" />

        <EditText
            android:layout_marginTop="450dp"
            android:id="@+id/editAddressLine2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="text"
            android:text="Address Line 2" />

        <EditText
            android:layout_marginTop="500dp"
            android:id="@+id/postcodeUser"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPostalAddress"
            android:text="Postcode" />

        <EditText
            android:layout_marginTop="550dp"
            android:id="@+id/county"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="text"
            android:text="County" />


    <!--</RelativeLayout>-->

    <!--<RelativeLayout-->

        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="0dp"-->
        <!--android:layout_below="@+id/relativeLayout1"-->
        <!--android:layout_marginTop="100dp">-->

        <Button
            android:layout_marginTop="600dp"
            android:id="@+id/btnAdd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="70dp"
            android:text="Add" />

        <Button
            android:layout_marginTop="650dp"
            android:id="@+id/btnView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_toRightOf="@+id/btnAdd"
            android:text="View Data" />

    </RelativeLayout>

</RelativeLayout>
</ScrollView>

1 个答案:

答案 0 :(得分:0)

您的问题是您只为所有EditText使用一个变量,即 editText 。因此,唯一有效使用的EditText是国家/地区(因为这是分配给 editText 变量的最后一个EditText。)

要解决此问题,您需要: -

  1. 为每个EditTexts和
  2. 声明变量
  3. 根据特定的EditText和
  4. 设置变量
  5. 从各自的EditText变量中检索值。
  6. e.g。你可以: -

    public class MainDatabase extends AppCompatActivity {
    
        private static final String TAG = "MainDatabase";
    
        DatabaseHelper mDatabaseHelper;
        private Button btnAdd, btnViewData;
        private EditText 
            editText,            
            editTextLast,        //<<<< ADDED
            editPassword,        //<<<< ADDED
            editPasswordConfirm, //<<<< ADDED
            editPhoneNumber,     //<<<< ADDED
            editEmailAddress,    //<<<< ADDED
            editAddressLine1,    //<<<< ADDED
            editAddressLine2,    //<<<< ADDED
            postcodeUser,        //<<<< ADDED
            country;             //<<<< ADDED
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            editText = findViewById(R.id.editText);
            editTextLast = findViewById(R.id.editTextLast); //<<<< CHANGED
            editPassword = findViewById(R.id.editPassword); //<<<< CHANGED
            editPasswordConfirm = findViewById(R.id.editPasswordConfirm); //<<<< CHANGED
            editPhoneNumber = findViewById(R.id.editPhoneNumber); //<<<< CHANGED
            editEmailAddress = findViewById(R.id.editEmailAddress); //<<<< CHANGED
            editAddressLine1 = findViewById(R.id.editAddressLine1); //<<<<CHANGED
            editAddressLine2 = findViewById(R.id.editAddressLine2); //<<<< CHANGEDX
            postcodeUser = findViewById(R.id.postcodeUser); //<<<< CHANGED
            country = findViewById(R.id.county); //<<<< CHANGED
            btnAdd = findViewById(R.id.btnAdd);
            btnViewData = findViewById(R.id.btnView);
            mDatabaseHelper = new DatabaseHelper(this);
    
            btnAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String newEntry = editText.getText().toString();
                    String newName = editTextLast.getText().toString(); //<<<< CHANGED
                    Integer newPass = Integer.parseInt(editPassword.getText().toString()); //<<<< CHANGED
                    String newPhone = editPhoneNumber.getText().toString(); //<<<< CHANGED
                    String newEmail = editEmailAddress.getText().toString(); //<<<< CHANGED
                    String newAdd1 = editAddressLine1.getText().toString(); //<<<< CHANGED
                    String newAdd2 = editAddressLine2.getText().toString(); //<<<< CHANGED
                    String newPC = postcodeUser.getText().toString(); //<<<< CHANGED
                    String newCounty = country.getText().toString(); //<<<< CHANGED
    
                    if (editText.length() != 0) {
                        AddData(newEntry, newName, newPass, newPhone, newEmail, newAdd1, newAdd2, newPC, newCounty);
    
    
                        editText.setText("");
                    } else {
                        toastMessage("You must put something in the text field!");
                    }
    
                }
            });
    
            btnViewData.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainDatabase.this, ListDataActivity.class);
                    startActivity(intent);
                }
            });
    
        }
    
    
    
        public void AddData(String newEntry, String newName, Integer newPass, String newPhone, String newEmail, String newAdd1, String newAdd2, String newPC, String newCounty) {
            boolean insertData = mDatabaseHelper.addData(newEntry,newName,newPass,newPhone,newEmail,newAdd1,newAdd2,newPC,newCounty);
    
    
            if (insertData) {
                toastMessage("Data Successfully Inserted!");
            } else {
                toastMessage("Something went wrong");
            }
        }
    
        /**
         * customizable toast
         * @param message
         */
        private void toastMessage(String message){
            Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
        }
    }
    

    注意以上是原则上的代码,尚未经过测试。因此,它可能包含一些错误。