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() を使用してこのリストを配列として変換します。次に、toString() を使用してこの配列を文字列として変換すると、java.lang.Object;..のような文字列が返されるため、これはデータベースにある名前ではありません。

そのため、指定された名前とデータベースから取得したアイテムのリストを比較するメソッドをもう 1 つ作成する必要があります。例のために。

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 に答える