How to use update with prevent duplicate entries SQLiteDatabase - java

hell... I in my code prevent duplicate entries but when update any field in this row tell my this name exist Although I'm in same row
as example have column firstName value = Mohamed ,column lastName value = taha and column Age value 25 when update Age tell my this firstName exist.
How to Solution this problem ?
This is my method:
public void saveStore(){
String namePermission =ETNamePermission.getText().toString().trim();
String notes = ETNotesPermission.getText().toString().trim();
boolean isExist = dbHelper.isExistNamePErmission(namePermission);
if ( intent == null && TextUtils.isEmpty(namePermission)|| TextUtils.isEmpty(namePermission) ){
ETNamePermission.requestFocus();
ETNamePermission.setError(getString(R.string.error_empty_text));
return;
}
if (intent == null) {
if (isExist ==true){
ETNamePermission.requestFocus();
ETNamePermission.setError(getString(R.string.error_exist_permission));
return;
}
ItemsStore itemSavePErmission = new ItemsStore();
itemSavePErmission.setNamePermission(namePermission);
itemSavePErmission.setNotes(notes);
if (itemSavePErmission == null) {
Toast.makeText(getContext(), getString(R.string.error_save_permission), Toast.LENGTH_LONG).show();
}else {
dbHelper.addPermission(itemSavePErmission);
Toast.makeText(getContext(), getString(R.string.save_permission), Toast.LENGTH_LONG).show();
dialog.dismiss();
}
}else {
ItemsStore itemUpdatePermision = new ItemsStore();
itemUpdatePermision.setId(intent.getInt(ID_PERMISSION));
itemUpdatePermision.setNamePermission(namePermission);
itemUpdatePermision.setNotes(notes);
boolean isExistForUpdated = dbHelper.isNamePermissioneUsedDailyMovements(intent.getInt(ID_PERMISSION));
if (isExistForUpdated == true){
Toast.makeText(getContext(), getString(R.string.this_permission_not_updated), Toast.LENGTH_SHORT).show();
return;
}
if (itemUpdatePermision != null){
dbHelper.updatePermission(itemUpdatePermision);
Toast.makeText(getContext(), getString(R.string.update_permission), Toast.LENGTH_LONG).show();
dialog.dismiss();
}else {
Toast.makeText(getContext(), getString(R.string.error_update_permission), Toast.LENGTH_LONG).show();
}
} }

Use Sqlite replace() method
db.replace(TABLE_NAME, null, contentValues);
But your table should have a unique or primary key. And replace method will check if a row exist with the given primary key. If exist the it will replace with updated value, if not then it will insert a new row with the given values.
Check this tutorial to learn about replace() method.

Related

While loop inside multiple if condition in android studio

I'm using while loop and inside am using two if statements.
while(cr.moveToNext()){
if(cr.getCount() > 0){
if((cr.getString(5).equals(username)) && cr.getString(6).equals(password)
&& cr.getString(14).equals("success")) {
String un = cr.getString(2);
String uc = cr.getString(1);
String rc = cr.getString(4);
......................
Toast.makeText(LoginActivity.this, "Successfully Logged In", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), Dashboard.class);
startActivity(intent);
} else{
Toast.makeText(LoginActivity.this, "Invalid Login", Toast.LENGTH_SHORT).show();
}
}
}
In this scenario, if I passed wrong value "Invalid Login" is executing many times [as it is inside while loop] and If I pass correct values both successfully login and Invalid login message is showing. How to make if condition to be properly work in this type of scenario...
Assuming you want to check that everything is in order before starting the activities you can do the loop twice, like below.
I also used do while, so as not to skip the first result.
private void handleCursor(Cursor cr){
boolean everythingGood = true;
do{
if (cr.getCount() > 14) { // <- if you are using cr.getString(14)
//to get "Success" string, then you should
//check for that too
if (!checkSuccess(cr) )
everythingGood = false; }
}else {
//not enough columns received.. assumed login fail.
//do your failure workflow
everythingGood = false;
}
} while(cr.moveToNext() && everythingGood);
if(everythingGood){
//second loop (no need to check any more, just spawn the activities)
cr.moveToFirst();
do{
createActivities(cr);
}while(cr.moveToNext();
}else {
handleFailure();
}
}
I moved your check condition out to another function to make it easier to see the while loop
private boolean checkSuccess(Cursor cr){
return cr.getString(5).equals(username)) && cr.getString(6).equals(password)
&& cr.getString(14).equals("success");
}
you can use break; or you can use a boolean flag variable , at first keep it true, then enter the conditions if it is true and once entered make the flag variable false in side that condition.
Boolean isValid;
isValid = true;
while(cr.moveToNext())
{
if (cr.getCount() > 0)
{
if ((cr.getString(5).equals(username))
&& cr.getString(6).equals(password) && cr.getString(14).equals("success"))
{
if (isValid)
{
isValid=false;
String un = cr.getString(2);
}
}
else { .......... }
}
}

Check on Text in sqlite

You do a favorite job, but when you click the Add to Favorites button, you do not have just one click and the text is added with each click
You can examine the text within the database, but after checking, the value returns 0 at a time and the text is added
public int get_check_List_Favorite(String nameFav) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor rev = db.rawQuery("SELECT * FROM myFavoriate WHERE nameFav Like'"+
nameFav +"",null);
int count = rev.getCount();
return count;
}
code button
case R.id.btn_favorite_text:
int check = db_sqlite.get_check_List_Favorite(nameFav);
Log.i("note", String.valueOf(check));
if (check > 0){
Toast.makeText(general.this, "I've been added before",
Toast.LENGTH_SHORT).show();
}else {
db_sqlite.addFavoriate(wordClass.getmTextV1());
Toast.makeText(general.this, "done added to favorites",
Toast.LENGTH_SHORT).show();
}
break;
the get_check_List_Favorite method is a call you can pass the parameter to search item in the database ret method is
public int get_check_List_Favorite(String nameFav) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor rev = db.rawQuery("SELECT * FROM myFavoriate WHERE Colomname Like '%"+nameFav+"%'",null);
int count = rev.getCount();
return count;
}
Try to change query
// modify below method in SQLite helper class
public String get_check_List_Favorite(String nameFav) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor rev = db.rawQuery("select * from myFavoriate where nameFav=?",new String[]{nameFav});
if (rev.getCount() > 0 ) {
rev.moveToFirst();
return rev.getString(rev.getColumnIndex("nameFav"));
}
return null;
}
// call above method from activity that will return username
case R.id.btn_favorite_text:
String username = db_sqlite.get_check_List_Favorite(wordClass.getmTextV1()));
if (username!=null){
Log.i("note", username);
Toast.makeText(general.this, "I've been added before",
.LENGTH_SHORT).show();
}else {
db_sqlite.addFavoriate(wordClass.getmTextV1());
Toast.makeText(general.this, "done added to favorites",
Toast.LENGTH_SHORT).show();
}
break;

Comparing Strings when one could be null

am presently trying to get a response from a server which contains a response code of "00,02" i used an if and else if statement to perform an action for each of this response but am getting null pointer for the first if statement
if (str.equalsIgnoreCase("02")){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}else if(str.equalsIgnoreCase("00")){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
A null-safe way of comparing strings would be:
if ("02".equalsIgnoreCase(str)) {
...
}
So just flip the strings in each of your conditions and you should be good to go!
Update your condition like this
if(str == null || str.length() == 0){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
else if (str.equalsIgnoreCase("02")){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}else if(str.equalsIgnoreCase("00")){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
else{
// Unknown code from server
}
You can use the TextUtils.isEmpty(str) function like so:
if (!TextUtils.isEmpty(str)){
if (str.equalsIgnoreCase("02")){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}else if(str.equalsIgnoreCase("00")){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
}
This function basically does this for you:
public static boolean isEmpty(#Nullable CharSequence str) {
if (str == null || str.length() == 0)
return true;
else
return false;
}
Which you could've done yourself, but it might be clearer this way.

If statement to show toast or continue to next activity

Not getting any errors im just stumped on this friggin if statement. I want the if statement to basically say if a check box is not checked and 3 EditTexts are empty then print a toast. Otherwise dont print the toast and continue to the next activity. First I turn the value of the checkbox into either t/f for true/false then execute my if statements as the following.
CheckBox noPtD1 = (CheckBox) findViewById(R.id.noPTD1);
String noPt_D1 = "f";
if (noPtD1.isChecked()) {
noPt_D1 = "t";
}
if (noPt_D1.equals("f") && day1_inst.equals("") || day1_uniform.equals("") ||
day1_location.equals(""))
{
Toast.makeText(getApplicationContext(), "Please Enter All Data Or Select the NO PT THIS DAY
checkbox!", Toast.LENGTH_LONG).show();
}
if(noPt_D1.equals("t") || !day1_inst.equals("") && !day1_uniform.equals("") &&
!day1_location.equals(""))
{
//PASS VARIABLES WITH INTENT
Intent intent = new Intent (OneWeekPlan_Start_Btn.this, Week1Day2.class);
//PASS VARIABLES FOR DAY 1
intent.putExtra("noPt_D1", noPt_D1);
intent.putExtra("day1_inst", day1_inst);
intent.putExtra("day1_uniform", day1_uniform);
intent.putExtra("day1_location", day1_location);
intent.putExtra("d1hours", d1hours);
intent.putExtra("d1min", d1min);
intent.putExtra("d1x1", d1x1);
intent.putExtra("d1x2", d1x2);
intent.putExtra("d1x3", d1x3);
intent.putExtra("d1x4", d1x4);
startActivity(intent);
}
This is working except for then I check the checkbox and and start the next activity with a button the next activity pops up like it is supposed to but the toast still appears. What did I mess up?
I got it I posted my answer below. But to rephrase exactly what my intent was:
If the user DOES NOT check the checkbox and leaves all 3 inputtexts blank show the toast and dont continue to next activity.
If the user DOES check the checkbox then DONT show the toast and continue to next activity.
Use brackets inside if statement
if (noPt_D1.equals("f") && (day1_inst.equals("") || day1_uniform.equals("") ||
day1_location.equals("")))
{
}
if(noPt_D1.equals("t") || (!day1_inst.equals("") && !day1_uniform.equals("") &&
!day1_location.equals("")))
{
}
You are making minor mistake in condition PLUS you need to use if - else block instead of 2 if blocks
//surround all && conditions inside separate braces
if (noPt_D1.equals("f") && (day1_inst.equals("") || day1_uniform.equals("") ||
day1_location.equals("")))
{
//show toast
}
else if(noPt_D1.equals("t") || (!day1_inst.equals("") && !day1_uniform.equals("") &&
!day1_location.equals("")))
{
//start activity
}
Hope this helps.
also try this. and its better to avoid including special characters for ur class name
if ("f".equals(noPt_D1) && "".equals(day1_inst) || "".equals(day1_uniform) ||
"".equals(day1_location))
{
Toast.makeText(getApplicationContext(), "Please Enter All Data Or Select the NO PT THIS DAY
checkbox!", Toast.LENGTH_LONG).show();
}
if("t".equals(noPt_D1) || !"".equals(day1_inst) && !"".equals(day1_uniform) &&
!"".equals(day1_location))
{
//PASS VARIABLES WITH INTENT
Intent intent = new Intent (OneWeekPlan_Start_Btn.this, Week1Day2.class);
//PASS VARIABLES FOR DAY 1
intent.putExtra("noPt_D1", noPt_D1);
intent.putExtra("day1_inst", day1_inst);
intent.putExtra("day1_uniform", day1_uniform);
intent.putExtra("day1_location", day1_location);
intent.putExtra("d1hours", d1hours);
intent.putExtra("d1min", d1min);
intent.putExtra("d1x1", d1x1);
intent.putExtra("d1x2", d1x2);
intent.putExtra("d1x3", d1x3);
intent.putExtra("d1x4", d1x4);
startActivity(intent);
}
Try to check EditText values via length() of String value. Secondly put && operator in if statement because you said in your question: if a check box is not checked and 3 EditTexts are empty then print a toast. Otherwise dont print the toast and continue to the next activity.
if (noPt_D1.equals("f") && day1_inst.trim().length() == 0 && day1_uniform.trim().length() == 0 &&
day1_location.trim().length() == 0)
{
Toast.makeText(getApplicationContext(), "Please Enter All Data", Toast.LENGTH_LONG).show();
}
else
{
Intent intent = new Intent (OneWeekPlan_Start_Btn.this, Week1Day2.class);
intent.putExtra("noPt_D1", noPt_D1);
intent.putExtra("day1_inst", day1_inst);
intent.putExtra("day1_uniform", day1_uniform);
intent.putExtra("day1_location", day1_location);
intent.putExtra("d1hours", d1hours);
intent.putExtra("d1min", d1min);
intent.putExtra("d1x1", d1x1);
intent.putExtra("d1x2", d1x2);
intent.putExtra("d1x3", d1x3);
intent.putExtra("d1x4", d1x4);
startActivity(intent);
}
EDIT:
Make sure you should declare your Strings which I am assuming are:
String day1_inst = your_editText_inst.getText().toString();
String day1_uniform = your_editText_uniform.getText().toString();
String day1_location = your_editText_location.getText().toString();
String noPt_D1 = "f";
if(your_check_box.isChecked())
{
noPt_D1 = "t";
}
else
{
noPt_D1 = "f";
}
Try using an OnCheckedChangeListener Listener, like whats shown below :
CheckBox noPtD1 = (CheckBox) findViewById(R.id.noPTD1);
String noPt_D1 = "f";
noPtD1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
noPt_D1 = "t";
} else {
noPt_D1 = "f";
}
}
});
Replace getApplicationContext() with this if you are in activity. getActivity() if you're in fragment.
Just figured it out thanks to M S Gadag =)
Basically I took the if statements and put the startActivity if statement on top. Then I added a variable to show that that statement had already been executed. Then I used that variable to start another if statement to decide whether or not to show the toast.
int showToast = 0;
if("t".equals(noPt_D1) || !"".equals(day1_inst) && !"".equals(day1_uniform) &&
!"".equals(day1_location))
{
//PASS VARIABLES WITH INTENT
Intent intent = new Intent (OneWeekPlan_Start_Btn.this, Week1Day2.class);
//PASS VARIABLES FOR DAY 1
intent.putExtra("noPt_D1", noPt_D1);
intent.putExtra("day1_inst", day1_inst);
intent.putExtra("day1_uniform", day1_uniform);
intent.putExtra("day1_location", day1_location);
intent.putExtra("d1hours", d1hours);
intent.putExtra("d1min", d1min);
intent.putExtra("d1x1", d1x1);
intent.putExtra("d1x2", d1x2);
intent.putExtra("d1x3", d1x3);
intent.putExtra("d1x4", d1x4);
startActivity(intent);
showToast = 1;
}
if ("f".equals(noPt_D1) && "".equals(day1_inst) || "".equals(day1_uniform) ||
"".equals(day1_location))
{
if (showToast !=1)
{
Toast.makeText(getApplicationContext(), "Please Enter All Data Or Select the NO PT THIS
DAY checkbox!", Toast.LENGTH_LONG).show();
}
}

Android - Select number syncced from facebook but returns null

So, I'm reading in phone numbers from the built-in contact list and the selected phone number should be put into a text box. This works all fine and dandy for phone numbers that come from google or have been put in manually by the user. However, when it comes to selecting a number that was synced from Facebook to the user's phone, the cursor returns NULL and the text box remains empty.
Here is the code that I'm using to select the number:
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver()
.query(uri,
new String[] {
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE, },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
txtPhoneNo.setText(number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
So, is there anything I can do that will allow me to get the Facebook synced phone numbers, or am I stuck with not being able to use those numbers?

Categories