Elsa
Elsa

Reputation: 35

How to get the data from the database created by another activity/ Fails to update data into database (Android studio,SQLite)

Thanks to Midhun MP, these 2 problems are solved! And I have a new question: I have 2 String to take over the data, one from what I entered, one from the database, I use the fonction equals() to make the comparison but they won't match, even though they are same numbers to me... I update below:

public void buttonOpen(View view) {
    EditText txtpass1 = (EditText) findViewById(R.id.password);  //on recuperer le mot de passeword
    String pass1str = txtpass1.getText().toString();

    Toast.makeText(ParCode.this, pass1str, Toast.LENGTH_LONG).show();//test

    Cursor allCode = new DataCode(this).getCode();//get the data from database using Cursor
    allCode.moveToFirst();
    while (!allCode.isAfterLast())
    {
        String code = allCode.getString(0);
        Log.i(code, "Code");
        allCode.moveToNext();
    }
    String pass2str = allCode.toString();//le data dans le bibliotheque

    if (pass1str.equals(pass2str)) {...}

Is the problem of the type of data?


Hello,guys. I'm a newb and my android-studio program is driving me crazy.
It's kind like a login program, I have 2 activities: The first one is for users to enter their password, I think it needs to get what user has entered and compare with the data in the database; The second one is for users to change password, I think this means update the data in the database
I've used sqlite to build a database for the code.(right now there is only one column for just one code but further there may be different users)

Here is my question:
1. According to my emulator, I can insert data into database, but fail to update it. Which is weird because when I click the update button, it tells me the code has been changed.
2. I need my first activity to get the code (which is saved in the database created by the second activity), and compare with what user has entered. But I don't know how to do this...
My database code:

public class DataCode extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Code4.dp";
public static final String TABLE_NAME = "Code_table";
public static final String COL_1 = "CODE";//a une seule ligne

public DataCode(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + " (CODE TEXT )");//create the table
}

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

//insert data
public boolean insertData(String CODE) {
    SQLiteDatabase db = this.getWritableDatabase();//insert to database
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_1, CODE);

    long result = db.insert(TABLE_NAME, null, contentValues);
    if (result == -1)
        return false;
    else
        return true;
}

//show data
public Cursor getCode(){
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);//store table in cursor
    return res;
}

//modifier code
public boolean updateCode(String CODE) {
    SQLiteDatabase db = this.getWritableDatabase();//create database
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_1, CODE);

    db.update(TABLE_NAME, contentValues, "code = ?", new String[]{ CODE });
    return true;
}
}

and my second activity's code (it fails to update the data):

public class ModifierC extends AppCompatActivity {
DataCode myDbC;//creat the database

EditText editCode;
Button Modifier;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_modifier_c);

    myDbC = new DataCode(this);//my database for code

    editCode = (EditText)findViewById(R.id.password2);
    Modifier = (Button)findViewById(R.id.buttonMP);
    buttonMP();//modifier le code

}

public void buttonMP(){//button to change the password

    Modifier.setOnClickListener(
            new View.OnClickListener() {

                public void onClick(View v) {

                    EditText txtpass2 = (EditText) findViewById(R.id.password2);

                    String pass2str = txtpass2.getText().toString();


                        Cursor res = myDbC.getCode();
                        if (res.getCount() == 0) {//if there is no data in the database, use the insert method
                            boolean isInserted = myDbC.insertData(editCode.getText().toString());
                            if (isInserted == true)
                                Toast.makeText(ModifierC.this, "Code enregistré", Toast.LENGTH_LONG).show();
                            else
                                Toast.makeText(ModifierC.this, "Pas encore de code", Toast.LENGTH_LONG).show();

                        }
                        else {//if there is already a code, use the update method
                            boolean isUpdated = myDbC.updateCode(editCode.getText().toString());//recuperer le code de password2
                            if (isUpdated == true)
                                Toast.makeText(ModifierC.this, "Code a changé", Toast.LENGTH_LONG).show();
                            else
                                Toast.makeText(ModifierC.this, "Error...", Toast.LENGTH_LONG).show();
                        }

                    }
                }

            }
    );
}
}

And for the first activity, I use Cursor to pass the data

public class ParCode extends AppCompatActivity {
DataCode myC;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_par_code);
}

public void buttonOpen(View view) {
    EditText txtpass1 = (EditText) findViewById(R.id.password);  //get what user has entered
    String pass1str = txtpass1.getText().toString();          

    Cursor coderes = myC.getCode();// search code in the database
    String pass2str = coderes.getString(0);

BUT it won't work, I think I may miss something.


Sorry this maybe a too long and very stupid question. However I have spend over one week on this, so I think I should ask for help. It's my first time to build an android app, and all my question is because of lacking of basic knowledge. But I really have to prepare for my test and have no time to stuck on this right now T T...So please give me some advice!!!
THANKS A LOT


the logcat gives me this:

06-03 06:22:58.224 27801-27801/com.example.android.sacconnecte I/4444: Code
06-03 06:22:58.327 27801-27839/com.example.android.sacconnecte W/EGL_emulation: eglSurfaceAttrib not implemented
06-03 06:22:58.327 27801-27839/com.example.android.sacconnecte W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad79f0a0, error=EGL_SUCCESS
06-03 06:23:08.396 27801-27839/com.example.android.sacconnecte E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab81b280

the first line is the code got from database. It works! just somehow it won't match with what I entered. Oh la la....

Upvotes: 1

Views: 483

Answers (1)

Midhun MP
Midhun MP

Reputation: 107211

The issue is happening because of the following line:

db.update(TABLE_NAME, contentValues, "code = ?", new String[]{ CODE });

Suppose your db consists of a value "Elsa", and now you are trying to update it to "Hello", the above code in sql query looks something similar to:

UPDATE Code_table SET CODE = 'Hello' WHERE code = 'Hello'

The above where clause will be false and the row won't be updated.

You need to use:

db.update(TABLE_NAME, contentValues, null, null);

The third and fourth parameters represents the WhereClause and WhereArgs. In your case you don't need to specify those (Because you don't have any unique or primary key fields defined).

Now the query will look like:

UPDATE Code_table SET CODE = 'Hello'

For getting the result using cursor, you can use the following code:

Cursor allCode = new DataCode().getCode();

allCode.moveToFirst();

while (!allCode.isAfterLast())
{
    String code = allCode.getString(0);
    Log.i(code, "Code");
    allCode.moveToNext();

}

Upvotes: 1

Related Questions