Added columns to SQLiteDatabase, can no longer read from it - javascript

My SQLiteDatabase was working fine with just 3 entries, the UUID, Title and Date, but ever since I added some more columns I am getting this error.
Not sure what it can be, I have read that 0,-1 means that the column cannot be read, but I have made sure to spell all my column names correctly.
CrimeCursorWrapper.java
public List<Crime> getCrimes() {
List<Crime> crimes = new ArrayList<>();
CrimeCursorWrapper cursor = queryCrimes(null, null);
try {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
crimes.add(cursor.getCrime());
cursor.moveToNext();
}
} finally{
cursor.close();
}
return crimes;
}
CrimeLab.java:
public Crime getCrime(UUID id) {
CrimeCursorWrapper cursor = queryCrimes(
CrimeTable.Cols.UUID + " = ?",
new String[] { id.toString() }
);
try {
if (cursor.getCount() == 0) {
return null;
}
cursor.moveToFirst();
return cursor.getCrime();
} finally {
cursor.close();
}
}
private static ContentValues getContentValues(Crime crime) {
ContentValues values = new ContentValues();
values.put(CrimeTable.Cols.UUID, crime.getId().toString());
values.put(CrimeTable.Cols.TITLE, crime.getTitle());
values.put(CrimeTable.Cols.DATE, crime.getDate().getTime());
values.put(CrimeTable.Cols.ACTTYPE, crime.getActType().toString());
values.put(CrimeTable.Cols.PLACE, crime.getPlace().toString());
values.put(CrimeTable.Cols.DURATION, crime.getDuration().toString());
values.put(CrimeTable.Cols.COMMENT, crime.getComment().toString());
return values;
}
private CrimeCursorWrapper queryCrimes(String whereClause, String[] whereArgs) {
Cursor cursor = mDatabase.query(
CrimeTable.NAME,
null, // Columns - null selects all columns
whereClause,
whereArgs,
null, // groupBy
null, // having
null // orderBy
);
return new CrimeCursorWrapper(cursor);
}
CrimeCursorWrapper.java:
public class CrimeCursorWrapper extends CursorWrapper{
public CrimeCursorWrapper(Cursor cursor) {
super(cursor);
}
public Crime getCrime() {
String uuidString = getString(getColumnIndex(CrimeTable.Cols.UUID));
String title = getString(getColumnIndex(CrimeTable.Cols.TITLE));
long date = getLong(getColumnIndex(CrimeTable.Cols.DATE));
String actType = getString(getColumnIndex(CrimeTable.Cols.ACTTYPE));
String place = getString(getColumnIndex(CrimeTable.Cols.PLACE));
String duration = getString(getColumnIndex(CrimeTable.Cols.DURATION));
String comment = getString(getColumnIndex(CrimeTable.Cols.COMMENT));
Crime crime = new Crime(UUID.fromString(uuidString));
crime.setTitle(title);
crime.setDate(new Date(date));
crime.setActType(actType);
crime.setPlace(place);
crime.setDuration(duration);
crime.setComment(comment);
return crime;
}
}
Crime.java:
public class Crime {
private UUID mId;
private String mTitle;
private Date mDate;
private String mActType;
private String mPlace;
private String mDuration;
private String mComment;
public Crime() {
this(UUID.randomUUID());
}
public Crime(UUID id) {
mId = id;
mDate = new Date();
}
public UUID getId() {
return mId;
}
public String getTitle() {
return mTitle;
}
public void setTitle(String title) {
mTitle = title;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
public String getPhotoFilename() {
return "IMG_" + getId().toString() + ".jpg";
}
public String getActType() {
return mActType;
}
public void setActType(String actType) {
mActType = actType;
}
public String getPlace() {
return mPlace;
}
public void setPlace(String place) {
mPlace = place;
}
public String getDuration() {
return mDuration;
}
public void setDuration(String duration) {
mDuration = duration;
}
public String getComment() {
return mComment;
}
public void setComment(String comment) {
mComment = comment;
}
}

It "CAN" be the reason: If you use your physical mobile device for debugging, after you change your database tables inside the code, delete your application's data from the mobile device and reinstall your apk (or press debug or run buttons). Database files are not updating automatically by Android Studio.

Did you change version of your database after adding more columns? It is mandatory.

Related

Error while inserting date and time in sql database table. I am getting error while trying to insert date and time in android studio sql database

Mainly the application I am buiding should be able to insert the title, description time and date the title is created. This is the database table I have created
for inserting title, content, date and time for an journal application.
While I was executing " the error as journal table column does not have a date " error occurred.
public class JournalDatabase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_NAME = "JOURNal_db";
private static final String DATABASE_TABLE = "Journal_table";
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_CONTENT = "content";
private static final String KEY_DATE = "date";
private static final String KEY_TIME= "time";
public JournalDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String create = " CREATE TABLE "+DATABASE_TABLE+"("+KEY_ID+"INTEGER PRIMARY KEY,"+
KEY_TITLE+"TEXT,"+
KEY_CONTENT+"TEXT,"+
KEY_DATE+"TEXT,"+
KEY_TIME+"TEXT" +")";
Log.d("dbHarry","Query being run is : "+ create);
db.execSQL(create);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
if (i >= i1)
return;
db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(db);
}
public void addJournal(Journal journal){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_TITLE,journal.getTitle());
contentValues.put(KEY_CONTENT,journal.getContent());
contentValues.put(KEY_DATE,journal.getDate());
contentValues.put(KEY_TIME,journal.getTime());
db.insert(DATABASE_TABLE,null,contentValues);
db.close();
}
public Journal getJournal(long id){
// select * from the databaseTable where id = 1
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(DATABASE_TABLE,new String[]{KEY_ID,KEY_TITLE,KEY_CONTENT,KEY_DATE,KEY_TIME},KEY_ID+"?",
new String[]{String.valueOf(id)},null,null,null);
if(null != cursor) {
cursor.moveToFirst();
}
return new Journal(cursor.getLong(0),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4));
}
public List<Journal> getJournals(){
SQLiteDatabase db = this.getReadableDatabase();
List<Journal> allJournals = new ArrayList<>();
// SELECT * FROM DATABASE NAME
String query = " SELECT * FROM " + DATABASE_TABLE;
Cursor cursor = db.rawQuery(query,null);
if (cursor.moveToFirst()) {
do {
Journal journal = new Journal();
journal.setID(cursor.getLong(0));
journal.setTitle(cursor.getString(1));
journal.setContent(cursor.getString(2));
journal.setDate(cursor.getString(3));
journal.setTime(cursor.getString(4));
allJournals.add(journal);
} while (cursor.moveToNext());
}
return allJournals;
}
}
Blockquote
Blockquote
This is the screenshot of error
According to your log, there is no column named "date" in your table, check it please.

How fix to SMS Retriever API

I wrote code for example "SMS Retreiver API" https://developers.google.com/identity/sms-retriever/request
but I don`t result which I wont
This code past to MainActivity.
SmsRetrieverClient client = SmsRetriever.getClient(this);
Task<Void> task = client.startSmsRetriever();
task.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
task.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
This code past to MySMSBroadcastReceiver.
public class MySMSBroadcastReceiver extends BroadcastReceiver {
String message;
Status status;
private static MessageListener mListener;
#Override
public void onReceive(Context context, Intent intent) {
if (SmsRetriever.SMS_RETRIEVED_ACTION.equals(intent.getAction())) {
Bundle extras = intent.getExtras();
status = (Status) extras.get(SmsRetriever.EXTRA_STATUS);
switch(status.getStatusCode()) {
case CommonStatusCodes.SUCCESS:
// Get SMS message contents
message = (String) extras.get(SmsRetriever.EXTRA_SMS_MESSAGE);
// Extract one-time code from the message and complete verification
// by sending the code back to your server.
break;
case CommonStatusCodes.TIMEOUT:
// Waiting for SMS timed out (5 minutes)
// Handle the error ...
break;
}
mListener.MySMSBroadcastReceiver(message);
}
}
public static void bindListener(MessageListener listener){
mListener = listener;
}
}
In my Manifest
<receiver android:name="ru.project.MBank.MySMSBroadcastReceiver" android:exported="true">
<intent-filter>
<action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED"/>
</intent-filter>
</receiver>
But result get nothing.
Help what do I do wrong?
I had same problem. First you need to generate a unique key (App Signature) that will identify message and your device. Once you generate key, your broadcaster will be able to detect message.
public class AppSignature extends ContextWrapper {
public static final String TAG = AppSignature.class.getSimpleName();
private static final String HASH_TYPE = "SHA-256";
public static final int NUM_HASHED_BYTES = 9;
public static final int NUM_BASE64_CHAR = 11;
public AppSignature(Context context) {
super(context);
}
/**
* Get all the app signatures for the current package
* #return
*/
public ArrayList<String> getAppSignatures() {
ArrayList<String> appCodes = new ArrayList<>();
try {
// Get all package signatures for the current package
String packageName = getPackageName();
PackageManager packageManager = getPackageManager();
Signature[] signatures = packageManager.getPackageInfo(packageName,
PackageManager.GET_SIGNATURES).signatures;
// For each signature create a compatible hash
for (Signature signature : signatures) {
String hash = hash(packageName, signature.toCharsString());
if (hash != null) {
appCodes.add(String.format("%s", hash));
}
}
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "Unable to find package to obtain hash.", e);
}
return appCodes;
}
private static String hash(String packageName, String signature) {
String appInfo = packageName + " " + signature;
try {
MessageDigest messageDigest = MessageDigest.getInstance(HASH_TYPE);
messageDigest.update(appInfo.getBytes(StandardCharsets.UTF_8));
byte[] hashSignature = messageDigest.digest();
// truncated into NUM_HASHED_BYTES
hashSignature = Arrays.copyOfRange(hashSignature, 0, NUM_HASHED_BYTES);
// encode into Base64
String base64Hash = Base64.encodeToString(hashSignature, Base64.NO_PADDING | Base64.NO_WRAP);
base64Hash = base64Hash.substring(0, NUM_BASE64_CHAR);
return base64Hash;
} catch (NoSuchAlgorithmException e) {
}
return null;
}
}
After this initiate this class in your firs activity.
Hope this will help you.

I have issues when trying to access and set my foreign key in my database

I get the following error when running my app using android studio.
Error
==============================================
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
My database is SQLite.
My app allows a user to register and login.
Sports app.
From here they can add "Players" to their team.
I have two tables set up in my db one for users and one for players with the "user_id" field from users table being used as the foreign key to link both dbs.
Basically only the logged in users who add a certain player can see that players information and not all others that other users created.
Originally the app was saving the players to the correct table.
However the foreign key was not getting filled.
I then re wrote the code to correct this.
However this is when i encountered this new problem.
Any help or advice at all is much appreciated.
1) DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "MyDB1.db";
private static final String TABLE_USER = "User";
private static final String COLUMN_USER_NAME = "User_name";
private static final String COLUMN_USER_ID = "User_id";
private static final String COLUMN_USER_EMAIL = "User_email";
private static final String COLUMN_USER_PASSWORD = "User_password";
private static final String TABLE_PLAYERS = "Player";
private static final String COLUMN_PLAYER_NAME = "Player_name";
private static final String COLUMN_PLAYER_AGE = "Player_age";
private static final String COLUMN_PLAYER_WEIGHT = "Player_weight";
private static final String COLUMN_PLAYER_HEIGHT = "Player_height";
private static final String COLUMN_PLAYER_ID = "Player_id";
private static final String FOREIGN_PLAYER_ID = COLUMN_USER_ID;
// private static final Image COLUMN_PLAYER_IMAGE ;
// Table 1 : Login/Register
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "(" + COLUMN_USER_NAME + " TEXT,"
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" + ")";
// Table 2 : Adding players
private String CREATE_PLAYER_TABLE = "CREATE TABLE " + TABLE_PLAYERS + "(" + COLUMN_PLAYER_NAME + " TEXT,"
+ COLUMN_PLAYER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ COLUMN_PLAYER_AGE + " INTEGER," + COLUMN_PLAYER_WEIGHT + " INTEGER," + COLUMN_PLAYER_HEIGHT + " INTEGER, " + FOREIGN_PLAYER_ID + " INTEGER," + "FOREIGN KEY(" + FOREIGN_PLAYER_ID + ") REFERENCES " + TABLE_USER + "(User_id) " + ")";
// Drop tables
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER ;
private String DROP_PLAYER_TABLE = "DROP TABLE IF EXISTS " + TABLE_PLAYERS ;
public DatabaseHelper(Context context){
//String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
db.execSQL(CREATE_PLAYER_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_USER_TABLE);
db.execSQL(DROP_PLAYER_TABLE);
onCreate(db);
}
// Adding a user to Users table
public void addUser(User user){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_NAME, user.getName());
values.put(COLUMN_USER_EMAIL, user.getEmail());
values.put(COLUMN_USER_PASSWORD, user.getPassword());
values.put(FOREIGN_PLAYER_ID, user.getForeignID());
db.insert(TABLE_USER, null, values);
db.close();
}
// Adding a player to players table
public void addPlayer(Player player) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// Table 2 : Add players info
values.put(COLUMN_PLAYER_NAME, player.getPlayerName());
values.put(COLUMN_PLAYER_AGE, player.getPlayerAge());
values.put(COLUMN_PLAYER_HEIGHT, player.getPlayerHeight());
values.put(COLUMN_PLAYER_WEIGHT, player.getPlayerWeight());
values.put(FOREIGN_PLAYER_ID, player.getForeignKey());
db.insert(TABLE_PLAYERS, null, values);
db.close();
}
// Checking the users email
public boolean checkUser(String email){
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getWritableDatabase();
String selection = COLUMN_USER_EMAIL + " = ?";
String[] selectionArgs = { email };
Cursor cursor = db.query(TABLE_USER,
columns,
selection,
selectionArgs,
null,
null,
null);
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0){
return true;
}
return false;
}
//
public String getColumnUserName(String email){
String user = "";
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getWritableDatabase();
String selection = COLUMN_USER_EMAIL + " = ?";
String[] selectionArgs = { email };
Cursor cursor = db.query(TABLE_USER,
columns,
selection,
selectionArgs,
null,
null,
null);
int cursorCount = cursor.getCount();
if (cursor.moveToFirst()) // data?{
user = cursor.getString(cursor.getColumnIndex("EMAIL"));
cursor.close(); // that's important too, otherwise you're gonna leak cursors
db.close();
if (cursorCount > 0){
return user;
}
return user;
}
// Checking the users email and password
public boolean checkUser(String email, String password){
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getWritableDatabase();
String selection = COLUMN_USER_EMAIL + " = ?" + " AND " + COLUMN_USER_PASSWORD + " =?";
String[] selectionArgs = { email, password };
Cursor cursor = db.query(TABLE_USER,
columns,
selection,
selectionArgs,
null,
null,
null);
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0){
return true;
}
return false;
}
}
2) Players.java
public class Players extends AppCompatActivity {
private Button insert;
private static final int PICK_IMAGE=100;
private String nameFromIntent = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_players);
//Open add players section
insert = (Button) findViewById(R.id.addPlayer);
insert.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View v)
{
openaAddPlayersActivity();
}
});
nameFromIntent = getIntent().getStringExtra("EMAIL");
}
private void openaAddPlayersActivity() {
Intent intent = new Intent(this, addPlayers.class );
String nameFromIntent = getIntent().getStringExtra("EMAIL");
intent.putExtra(("EMAIL") ,nameFroenter code heremIntent);
startActivity(intent);
}
}
3)addPlayers.java
public class addPlayers extends AppCompatActivity implements View.OnClickListener{
private Button insert;
private static final int PICK_IMAGE=100;
private final AppCompatActivity activity = addPlayers.this;
private EditText editTextPlayerName;
private EditText editTextPlayerAge;
private EditText editTextPlayerWeight;
private EditText editTextPlayerHeight;
private TextInputEditText textInputEditTextEmail;
private Inputvalidation inputvalidation;
private DatabaseHelper databaseHelper;
private Player player;
private Button appCompatButtonRegister;
private User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_players);
// insert = (Button) findViewById(R.id.profilePicture);
// insert.setOnClickListener(new View.OnClickListener()
getSupportActionBar().hide();
initViews();
initListeners();
initObjects();
}
private void initViews() {
editTextPlayerName = (EditText) findViewById(R.id.playerName);
editTextPlayerAge = (EditText) findViewById(R.id.playerAge);
editTextPlayerHeight = (EditText) findViewById(R.id.playerHeight);
editTextPlayerWeight = (EditText) findViewById(R.id.playerWeight);
textInputEditTextEmail = (TextInputEditText) findViewById(R.id.enterEmail);
appCompatButtonRegister = (Button) findViewById(R.id.savePlayer);
}
private void initListeners() {
appCompatButtonRegister.setOnClickListener(this);
}
private void initObjects() {
inputvalidation = new Inputvalidation(activity);
databaseHelper = new DatabaseHelper(activity);
player = new Player ();
}
// Table 2 : Add players info
#Override
public void onClick(View v) {
// Intent intent = new Intent(Intent.ACTION_PICK, Uri.parse("content://media/internal/images/media"));
//startActivityForResult(intent, PICK_IMAGE);
switch (v.getId()){
case R.id.savePlayer:
postDataToSQLite();
break;
}
}
private void postDataToSQLite() {
if(!databaseHelper.checkUser(editTextPlayerName.getText().toString().trim()))
//textInputEditTextPassword.getText().toString().trim()))
{
Bundle email= getIntent().getExtras();
String a = databaseHelper.getColumnUserName(email.getString("EMAIL"));
player.setPlayerName(editTextPlayerName.getText().toString().trim());
player.setPlayerAge(Integer.parseInt(editTextPlayerAge.getText().toString().trim()));
player.setPlayerHeight(Integer.parseInt(editTextPlayerHeight.getText().toString().trim()));
player.setPlayerWeight(Integer.parseInt(editTextPlayerWeight.getText().toString().trim()));
player.setForeignKey(Integer.parseInt(a));
//Integer.parseInt(databaseHelper.getColumnUserName(ContactsContract.CommonDataKinds.Email.getString("EMAIL"))));
databaseHelper.addPlayer(player);
Snackbar.make(findViewById(R.id.addPlayer), R.string.success_player_message,Snackbar.LENGTH_LONG).show();
// emptyEditText();
Intent accountIntent = new Intent(activity, Players.class);
accountIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim());
//emptyInputEditText();
startActivity(accountIntent);
}
//else {
// Snack Bar to show error message that record already exists
// Snackbar.make(findViewById(R.id.Register), getString(R.string.error_email_exists), Snackbar.LENGTH_LONG).show();
// }
}
/*protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK && requestCode==PICK_IMAGE){
Uri uri = data.getData();
String x = getPath(uri);
Toast.makeText(getApplicationContext(), x, Toast.LENGTH_LONG).show();
}
}
private String getPath(Uri uri) {
if(uri==null)return null;
String [] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
if(cursor!=null){
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return uri.getPath();
}
*/
}
4) Login.java
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private final AppCompatActivity activity = LoginActivity.this;
private NestedScrollView nestedScrollView;
private TextInputLayout textInputLayoutEmail;
private TextInputLayout textInputLayoutPassword;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private AppCompatButton appCompatButtonLogin;
private AppCompatTextView textViewLinkRegister;
private Inputvalidation inputvalidation;
private DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
initViews();
initListeners();
initObjects();
}
private void initViews() {
textInputLayoutEmail = findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword = findViewById(R.id.textInputLayoutPassword);
textInputEditTextEmail = findViewById(R.id.enterEmail);
textInputEditTextPassword = findViewById(R.id.enterPassword);
appCompatButtonLogin = findViewById(R.id.Login);
textViewLinkRegister = findViewById(R.id.textViewLinkRegister);
}
private void initListeners() {
appCompatButtonLogin.setOnClickListener(this);
textViewLinkRegister.setOnClickListener(this);
}
private void initObjects() {
databaseHelper = new DatabaseHelper(activity);
inputvalidation = new Inputvalidation(activity);
}
#Override
public void onClick(View v){
switch (v.getId()){
case R.id.Login:
verifyFromSQLite();
break;
case R.id.textViewLinkRegister:
Intent intentRegister = new Intent(getApplicationContext(), Register.class);
startActivity(intentRegister);
break;
}
}
private void verifyFromSQLite() {
if (!inputvalidation.isInputEditTextFilled(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))){
return;
}
if (!inputvalidation.isInputEditTextEmail(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))){
return;
}
if (!inputvalidation.isInputEditTextFilled(textInputEditTextPassword, textInputLayoutPassword, getString(R.string.error_message_password))){
return;
}
if(databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim(), textInputEditTextPassword.getText().toString().trim()))
{
Intent accountIntent = new Intent(activity, LoggedIn.class);
accountIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim());
emptyInputEditText();
startActivity(accountIntent);
}else {
Snackbar.make(findViewById(R.id.Login), R.string.error_valid_email_password,Snackbar.LENGTH_LONG).show();
//nestedScrollView, getString(R.string.error_valid_email_password), Snackbar.LENGTH_LONG).show();
}
}
private void emptyInputEditText() {
textInputEditTextEmail.setText(null);
textInputEditTextPassword.setText(null);
}
}
I believe that your issue may be that your foreign key is acting as it should and that a conflict is being raised because the the player passed to the addPlayer method doesn't appear to have the user set (unless dome within the construction of the Player object).
That is user may well be null or some other value that is not a value that is stored in the User_id column in the User table.
That is you only appear to pass the email from activity to activity and then only use the checkUser (only returns a boolean) and the getColumnsUserName (only returns a String that appears to be the email that was found according to the email used as the search argument).
The User_id however MUST be an integer value for it to be a valid User_id column in the User table.
That is as the User_id column being defined using INTEGER PRIMARY KEY (with or without AUTOINCREMENT) is an alias of the hidden rowid column and MUST be an INTEGER value (SQLite Autoincrement P.S. additionally note the summary in regards to using AUTOINCREMENT).
Determining the issue
I would suggest placing a breakpoint on the line db.insert(TABLE_PLAYERS, null, values); in the DatabaseHelper and running in Debug, when the breakpoint is reached to then inspect the value of foreignId in the player object.
You may wish to read Debug your app
However, if the cause is as suspected I also believe that the Stack-trace should also indicate the CONFLICT.
Personally rather than passing the email from activity to activity I'd suggest passing the User_id value as this will be UNIQUE and is also the most efficient means to locate the respective row as per :-
The data for rowid tables is stored as a B-Tree structure containing
one entry for each table row, using the rowid value as the key. This
means that retrieving or sorting records by rowid is fast. Searching
for a record with a specific rowid, or for all records with rowids
within a specified range is around twice as fast as a similar search
made by specifying any other PRIMARY KEY or indexed value.
ROWIDs and the INTEGER PRIMARY KEY
Additonal
There are two issues that will each result in the index -1 issue.
The -1 issue itself is because the Cursor getColumnIndex method returns -1 if the column passed to the method does not exist in the Cursor (note a Cursor only has the columns that have been specified).
The first issue is with the line :-
user = cursor.getString(cursor.getColumnIndex("EMAIL"));
There is no such column in the user table so this would always fail. Changing this to :-
user = cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL));
will specify a column that is in the table.
The second issue is that although COLUMN_USER_EMAIL is a valid column in the table, that column is not included in the Cursor.
To include that column in the Cursor then change :-
String[] columns = {
COLUMN_USER_ID
};
to :-
String[] columns = {
COLUMN_USER_ID,
COLUMN_USER_EMAIL
};
or to :-
String[] columns = {"*" }; //<<<<<<<<<< * means ALL columns
or instead change :-
Cursor cursor = db.query(TABLE_USER,
columns,
selection,
selectionArgs,
null,
null,
null);
int cursorCount = cursor.getCount();
to
Cursor cursor = db.query(TABLE_USER,
null, //<<<<<<<<<< null equates to * and thus ALL columns
selection,
selectionArgs,
null,
null,
null);
So the app is now working correctly after a rebuild.
Pretty strange behavior but i wont complain.
Thanks for you help.
Eamon

p:commandButton execution order of events

I am using PrimeFaces 6.0 components:
<p:commandButton type="submit" value="Create Customer"
icon="ui-icon-check"
actionListener="#{newCustomerBean.saveNewCustomer}"
update = "#form"
oncomplete="ajaxUploadFile();"/>
<p:inputText id="saveCustomerId" value ="#{newCustomerBean.savedKundeId}"/>
and I want to execute the following sequence of actions with them:
1.) Execute the actionListener method on the backing bean to save a customer;
2.) Update the form field saveCustomerId with the id of the customer that is saved on step (1). The actionListener method generates a customer Id after the successful save and stores is as a bean property;
3.) Execute the Java Script method ajaxUploadFile()
According to the link
Execution order of events when pressing PrimeFaces p:commandButton
this sequence shall be as I have imagined.
However, in reality, the method
ajaxUploadFile()
is called BEFORE the input field with id saveCustomerId is updated.
Could you help me get the right sequence?
Here is the backing bean:
#ManagedBean
#ViewScoped
public class NewCustomerBean implements Serializable {
public enum KundeTyp {
TYP_NATPERS("Nat. Person"), TYP_FIRMA("Firma");
private String value;
private KundeTyp(String value) {
this.value = value;
}
#Override
public String toString() {
return value;
}
}
private KundeTyp custmerType;
private Map<String, KundeTyp> custmerTypes;
private long savedKundeId;
#Inject
private KundeDBService kundeService;
private String vorname;
private String addresse;
private String steuerNummer;
private String kundeTyp = Integer.MIN_VALUE + "";
#PostConstruct
public void init() {
custmerTypes = new HashMap<String, KundeTyp>();
custmerTypes.put(KundeTyp.TYP_NATPERS.value, KundeTyp.TYP_NATPERS);
custmerTypes.put(KundeTyp.TYP_FIRMA.value, KundeTyp.TYP_FIRMA);
}
public KundeTyp getCustmerType() {
return custmerType;
}
public void setCustmerType(KundeTyp custmerType) {
this.custmerType = custmerType;
}
public Map<String, KundeTyp> getCustmerTypes() {
return custmerTypes;
}
public void setCustmerTypes(Map<String, KundeTyp> custmerTypes) {
this.custmerTypes = custmerTypes;
}
public String getVorname() {
return vorname;
}
public void setVorname(String vorname) {
this.vorname = vorname;
}
public String getAddresse() {
return addresse;
}
public void setAddresse(String addresse) {
this.addresse = addresse;
}
public String getSteuerNummer() {
return steuerNummer;
}
public void setSteuerNummer(String steuerNummer) {
this.steuerNummer = steuerNummer;
}
public String getKundeTyp() {
return kundeTyp;
}
public void setKundeTyp(String kundenTyp) {
this.kundeTyp = kundenTyp;
}
public String saveNewCustomer(ActionEvent e) {
Kunde neuerKunde = null;
switch (this.custmerType) {
case TYP_NATPERS: {
neuerKunde = new NatuerlichePerson();
break;
}
case TYP_FIRMA: {
neuerKunde = new Firma();
((Firma) neuerKunde).setSteuerNummer("123456");
break;
}
}
neuerKunde.setVorname(vorname);
neuerKunde.setAdresse(this.addresse);
try {
savedKundeId = kundeService.saveKunde(neuerKunde);
} catch (ServiceException se) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error",
"Unable to save the new customer: " + se.getMessage()));
}
return null;
}
public long getSavedKundeId() {
return savedKundeId;
}
public void setSavedKundeId(long savedKundeId) {
this.savedKundeId = savedKundeId;
}
}
I would propose a work-around here, since I was not able to find a solution.
Instead of updating the customerId on the front-end, we put it as a session attribute in the HttpSession.
Then, in the UploadServlet, which handles the file upload, we read this attribute and save the image under this customerId.

Can't connect IExtension object to BrowserHelperObject

I'm trying to call a BHO plugin function from javascript, that BHO injected to page.
But:
console.log(window.myExtension) is "none" or "undefined"
OnDocumentComplete fires not on each browser start. (it's because of IE?)
OnDocumentComplete not fires on F5, just if set cursor in address field and press Enter (and see 2nd)
Complete code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Expando;
using SHDocVw;
using mshtml;
using Microsoft.Win32;
using INISpace;
namespace IEPlugin
{
[ComVisible(true),
Guid("4C1D2E51-018B-4A7C-8A07-618452573E42"),
InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IExtension
{
[DispId(1)]
void alert(string message);
}
// IObjectWithSite GUID
[ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("FC4801A3-2BA9-11CF-A229-00AA003D7352")]
public interface IObjectWithSite
{
[PreserveSig]
int SetSite([MarshalAs(UnmanagedType.IUnknown)]object site);
[PreserveSig]
int GetSite(ref Guid guid, out IntPtr ppvSite);
}
[ComVisible(true),
Guid("DA8EA345-02AE-434E-82E9-448E3DB7629E"),
ClassInterface(ClassInterfaceType.None), ProgId("MyExtension"),
ComDefaultInterface(typeof(IExtension))]
public class BrowserHelperObject : IObjectWithSite, IExtension
{
private WebBrowser webBrowser;
public void alert(string message) { System.Windows.Forms.MessageBox.Show("BHO: " + message); }
public void OnDocumentComplete(dynamic frame, ref dynamic url)
{
if (!ReferenceEquals(frame, webBrowser))
{
return;
}
dynamic window = webBrowser.Document.parentWindow;
IExpando windowEx = (IExpando)window;
windowEx.AddProperty("myExtension");
//window.myExtension = this; crash that piece of shit
this.alert("frame IS browser" + windowEx);
HTMLDocument document = (HTMLDocument)webBrowser.Document;
IHTMLScriptElement scriptObject = (IHTMLScriptElement)document.createElement("script");
scriptObject.type = #"text/javascript";
scriptObject.text = "console.log(window.myExtension);";
document.appendChild((IHTMLDOMNode)scriptObject);
}
public int SetSite(object site)
{
if (site != null)
{
webBrowser = (WebBrowser)site;
webBrowser.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
}
else
{
webBrowser.DocumentComplete -= new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
webBrowser = null;
}
return 0;
}
public int GetSite(ref Guid guid, out IntPtr ppvSite)
{
IntPtr punk = Marshal.GetIUnknownForObject(webBrowser);
int hr = Marshal.QueryInterface(punk, ref guid, out ppvSite);
Marshal.Release(punk);
return hr;
}
public const string BHO_REGISTRY_KEY_NAME = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Browser Helper Objects";
[ComRegisterFunction]
public static void RegisterBHO(Type type)
{
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(BHO_REGISTRY_KEY_NAME, true);
if (registryKey == null)
registryKey = Registry.LocalMachine.CreateSubKey(BHO_REGISTRY_KEY_NAME);
string guid = type.GUID.ToString("B");
RegistryKey ourKey = registryKey.OpenSubKey(guid);
if (ourKey == null)
{
ourKey = registryKey.CreateSubKey(guid);
}
ourKey.SetValue("NoExplorer", 1, RegistryValueKind.DWord);
registryKey.Close();
ourKey.Close();
}
[ComUnregisterFunction]
public static void UnregisterBHO(Type type)
{
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(BHO_REGISTRY_KEY_NAME, true);
string guid = type.GUID.ToString("B");
if (registryKey != null)
registryKey.DeleteSubKey(guid, false);
}
}
}

Categories