0

又是我,大卫。我只是想知道我的代码是否正确。我试图弄清楚数据库(Database_Handler.java)是否可以检查名为label_input的EditText。如果它已经存在于数据库中,则取消注册。但是,我的问题是,即使没有错误,条件也会忽略并自动跳转到else语句。希望你能帮助我,并提前感谢。

这是我的代码(Database_Handler.java):

//Variables
private Button add_button, proceed_to_player_spinner_menu;
private EditText label_input;
//private SQLiteDatabase datab;

//Response
public final static String EXTRA_MESSAGE_1 = "com.example.databasetestvertwo.MESSAGE1";
public final static String EXTRA_MESSAGE_2 = "com.example.databasetestvertwo.MESSAGE2";
public final static String EXTRA_MESSAGE_3 = "com.example.databasetestvertwo.MESSAGE3";




@Override
public void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);

    setContentView(R.layout.register_menu);

    //Setting for the players' list.
    add_button = (Button) findViewById(R.id.register_name);
    proceed_to_player_spinner_menu = (Button) findViewById(R.id.Proceed_Button_to_Spinner);
    label_input = (EditText) findViewById(R.id.Name_of_Player_Text_Box);

    //Function for Buttons to be add as a new player's name.
    add_button.setOnClickListener(new OnClickListener() 
    {

        public void onClick(View v) 
        {

            String label = label_input.getText().toString();

            //Here's the process on how to register in the database.
            if(label.trim().length() > 0)
            {
                //Database Handler from Class (Database_Handler.java)
                Database_Handler db = new Database_Handler(getApplicationContext());

                //Inserting new label into the database.
                //db.insertLabel(label);

                if(db.getAllLabels().toArray().toString().equals(label))
                {
                    Toast.makeText(getApplicationContext(), "Name existed.", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Name available!", Toast.LENGTH_SHORT).show();
                }

                //Message Confirmation
                //Toast.makeText(getApplicationContext(), "Player name " + label + " have been confirmed!", Toast.LENGTH_SHORT).show();

                //After typing, the text field is set to blank.
                //label_input.setText("");

                //Normally, most smartphones and tablets only have a virtual keyboard.
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(label_input.getWindowToken(), 0);

                //loadSpinnerData();
            }

            else //If the input is null...
            {
                Toast.makeText(getApplicationContext(), "Please enter your name.", Toast.LENGTH_SHORT).show();
            }

        }

    });

    proceed_to_player_spinner_menu.setOnClickListener(new OnClickListener() 
    {

        public void onClick(View v) 
        {

            startActivity(new Intent(from_3_players.this, Player_at_3_Spinner_Menu.class));

        }

    });

}

...以及Database_Handler.java的代码

//Main Variables for the Database Handler
private static final int DATABASE_VERSION = 1; //Version of the Database
private static final String DATABASE_NAME = "spinnerExample"; //Name of the Database
public static final String TABLE_LABELS = "labels"; // Table Name

//Columns for the Database
public static final String KEY_ID = "id";
private static final String KEY_NAME = "name";





public Database_Handler(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}






@Override
public void onCreate(SQLiteDatabase db) //Used for creating a table. 
{

    //Create Table Query Category 
    /*
     * 
     * 
     *      WARNING! Under CREATE_CATEGORIES_TABLE, strictly type the exact words on
     *      all 4 values with quotations, even the space. Exception only is the name
     *      from the variable names under "private static final String" here.  
     * 
     * 
     */
    String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "(" + KEY_ID +
            " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";

    db.execSQL(CREATE_CATEGORIES_TABLE); //Executes the query.

}





@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) //Updates the info.
{

    //Drops the old existing table.
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);

    //Creates table again.
    onCreate(db);

}





/*
 * 
 *             The next section will create a new label into the tables.
 *          This allows the database to harvest the identifier for each
 *          column. And, the database must set a list of person so that
 *          it applies in an infinite number of registration.  
 * 
 */





//Inserts a new label into the table.
public void insertLabel(String label)
{

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, label);

    //Inserting Row
    db.insert(TABLE_LABELS, null, values);
    db.close(); //Always close the database to prevent running dynamically. It has a pause to process one at a time.

}





//Returns all labels stored in the database.
public List<String> getAllLabels()
{

    List<String> labels = new ArrayList<String>(); //This must be return.

    //Select all Query it have.
    String selectQuery = "SELECT * FROM " + TABLE_LABELS;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    //Do the loop by rows to add new in the database
    if(cursor.moveToFirst())
    {
        do
        {
            labels.add(cursor.getString(1));
        }

        while(cursor.moveToNext());
    }

    //Always close the connections.
    cursor.close();
    db.close();

    //Return the labels for feedback and response. the "return" keyword can be like a value set for process.
    return labels;

}
4

2 回答 2

1

您试图将数组与您的标签进行比较。

db.getAllLabels().toArray().toString() 在这里,您从数据库中获取名称列表作为 list(List),然后使用 toArray() 将此列表转换为 Array。然后你使用 toString() 将此数组转换为字符串,这将返回类似java.lang.Object;..的字符串,所以这不是数据库中的任何名称。

因此必须编写另一种方法来比较给定名称与从数据库中检索到的项目列表。例如。

if (isNameExists(label)) {
     //show positive Toast  
} else {
    //show negative Toast
}

// 方法 isNameExists() 如下

private boolean isNameExists(String name) {
    Database_Handler db = new Database_Handler(getApplicationContext());

    List<String> nameList = db.getAllLabels();

    for(String nameInDB : nameList) {
         if (nameInDB.equals(name)
             return true;
    }

    return false;

}
于 2012-07-31T09:54:19.000 回答
1
  public class Database {
    private static final String TAG = "DbAdapter";

    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    public static final String TABLE_COMMENTS = "tablename";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_COMMENT = "comment";

    private static final String DATABASE_NAME = "databasename";
    private static final int DATABASE_VERSION = 1;

    private final Context mCtx;

    private static class DatabaseHelper  extends SQLiteOpenHelper 
    {


        // Database creation sql statement
        private static final String DATABASE_CREATE = "CREATE  TABLE tablename (id INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL , column1 INTEGER, column2 TEXT, column3 TEXT, column4 TEXT, column5 TEXT, column6 NUMERIC)";

        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase database) {
            database.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(DatabaseHelper.class.getName(),
                    "Upgrading database from version " + oldVersion + " to "
                            + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
            onCreate(db);
        }



    }




    public Database(Context c)
    {
        this.mCtx = c;
    }


    public void open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
    }

    public void close() {
        mDbHelper.close();
    }

    public void inset(ContentValues cv) 
    {
        mDb.insert(TABLE_COMMENTS, null, cv);
    }

    public Cursor getdata()
    {
        Cursor c = mDb.rawQuery("SELECT * FROM tablename", null);
        return c;
    }

    public Cursor getById(int index)
    {
        Cursor c = mDb.rawQuery("SELECT * FROM tablename where field ="+index, null);
        return c;
    }
    public void deletedata(int index)
    {
        mDb.rawQuery("delete from tablename where id ="+index, null);

    }
public boolean checkRegistration(String name)
        {

            Cursor c = mDb.rawQuery("SELECT * FROM tablename where column name= "+name, null);
                    int count = c.getCount;
                    c.close();
            if(count > 0)
                    {
                       return false;
                    }
                    else
                    {
                       return true;
                    }
     }


}


Database db =new Database(this);
db.open();
if(db.checkRegistration(str))
{
   //please register this user.
}
else
{
   //this user already register
}
db.close();
于 2012-07-31T10:07:58.170 回答