Adding and updating details to SQLite database

Kdawg92

I have two methods in MyDBHandler class, one for adding details and one for updating details. The user fills in a form and their details are added to the database and outputed as a listView. I want the user to be able to fill in the same form again to update their details. My problem is that when I first install the app then there are no records to update so I have to use the addDetails method which keeps adding new rows into the database when what I want to do is update the details using the updateDetails method. I can't update the details if there is nothing to update when the app is first installed.

addDetails Method

//Add a new row to the database
public void addDetails(Details details) {
    ContentValues values = new ContentValues();

    values.put(COLUMN_FIRSTNAME, details.getFirstname());
    values.put(COLUMN_SURNAME, details.getSurname());
    values.put(COLUMN_PHONE, details.getPhone());
    values.put(COLUMN_EMAIL, details.getEmail());
    values.put(COLUMN_ADDRESS1, details.getAddress1());
    values.put(COLUMN_ADDRESS2, details.getAddress2());

    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_DETAILS, null, values);
    db.close();
}

updateDetails method

//Updates user details
public void updateDetails(Details details){
    ContentValues values = new ContentValues();

    //Take new values from the details object provided
    values.put(COLUMN_FIRSTNAME, details.getFirstname());
    values.put(COLUMN_SURNAME, details.getSurname());
    values.put(COLUMN_PHONE, details.getPhone());
    values.put(COLUMN_EMAIL, details.getEmail());
    values.put(COLUMN_ADDRESS1, details.getAddress1());
    values.put(COLUMN_ADDRESS2, details.getAddress2());

    SQLiteDatabase db = this.getWritableDatabase();

    //Update the details object where id matches
    db.update(TABLE_DETAILS, values, COLUMN_ID + "='" + details._id + "'", null);


    db.close();

}

FragmentTab1 class

import com.astuetz.viewpager.extensions.sample.*;

import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View.OnClickListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.widget.Toast;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;


public class FragmentTab1 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment1, container, false);
    super.onCreate(savedInstanceState);





    //setContentView(R.layout.fragment1);
    firstName = (TextView) rootView.findViewById(R.id.firstName);
    editTextName = (EditText) rootView.findViewById(R.id.editTextName);
    textView5 = (TextView) rootView.findViewById(R.id.surName);
    editTextSurname = (EditText) rootView.findViewById(R.id.editTextSurname);
    textView4 = (TextView) rootView.findViewById(R.id.mobile);
    editTextMobile = (EditText) rootView.findViewById(R.id.editTextMobile);
    textView2 = (TextView) rootView.findViewById(R.id.Email);
    editTextEmail = (EditText) rootView.findViewById(R.id.editTextEmail);
    textView3 = (TextView) rootView.findViewById(R.id.address1);
    editTextAddress1 = (EditText) rootView.findViewById(R.id.editTextAddress1);
    textView6 = (TextView) rootView.findViewById(R.id.address2);
    editTextAddress2 = (EditText) rootView.findViewById(R.id.editTextAddress2);

    dbHandler = new MyDBHandler(getActivity(), null, null, 1);



    Button addButtonClicked = (Button)rootView.findViewById(R.id.addButtonClicked);
    addButtonClicked.setOnClickListener(new OnClickListener(){
        public void onClick(View v)
        {
            addButtonClicked(v);
        }
    });

    return rootView;
}



TextView firstName;
EditText editTextName;

TextView textView5;
EditText editTextSurname;

TextView textView4;
EditText editTextMobile;

TextView textView2;
EditText editTextEmail;

TextView textView3;
EditText editTextAddress1;

TextView textView6;
EditText editTextAddress2;

MyDBHandler dbHandler;



//validate email provided by user
private boolean isValidEmail(String email) {
    String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
            + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    Pattern pattern = Pattern.compile(EMAIL_PATTERN);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}



//Add details to the database and shared preferences
public void addButtonClicked(View view) {



    final String email = editTextEmail.getText().toString();
    if (!isValidEmail(email))
    {
        editTextEmail.setError("Invalid Email");
        Toast.makeText(getActivity().getApplicationContext(), "Invalid email format",
                Toast.LENGTH_LONG).show();

    }
    else if( editTextName.getText().toString().length() == 0 )
    {
        editTextName.setError("First name is required!");
        Toast.makeText(getActivity().getApplicationContext(), "First name is required",
                Toast.LENGTH_LONG).show();
    }
    else if( editTextSurname.getText().toString().length() == 0 )
    {
        editTextSurname.setError("Surname is required!");
        Toast.makeText(getActivity().getApplicationContext(), "Surname is required",
                Toast.LENGTH_LONG).show();
    }
    else if( editTextMobile.getText().toString().length() == 0 || editTextMobile.getText().toString().length() < 10 )
    {
        editTextMobile.setError("Not a valid number!");
        Toast.makeText(getActivity().getApplicationContext(), "Not a valid number",
                Toast.LENGTH_LONG).show();
    }
    else if( editTextAddress1.getText().toString().length() == 0 )
    {
        editTextAddress1.setError("Address Line 1 is required!");
        Toast.makeText(getActivity().getApplicationContext(), "Address Line 1 is required",
                Toast.LENGTH_LONG).show();
    }
    else if( editTextAddress2.getText().toString().length() == 0 )
    {
        editTextAddress2.setError("Address Line 2 is required!");
        Toast.makeText(getActivity().getApplicationContext(), "Address Line 2 is required",
                Toast.LENGTH_LONG).show();
    }
    else
    {
        Details details = new Details();
        details.set_id(1);
        details.setFirstname(editTextName.getText().toString());
        details.setSurname(editTextSurname.getText().toString());
        details.setPhone(editTextMobile.getText().toString());
        details.setEmail(editTextEmail.getText().toString());
        details.setAddress1(editTextAddress1.getText().toString());
        details.setAddress2(editTextAddress2.getText().toString());
        dbHandler.addDetails(details);
        Toast.makeText(getActivity().getApplicationContext(), "Details saved successfully",
                Toast.LENGTH_LONG).show();
    }

}

}
Mounir Elfassi

you have to check if the table is empty, to do so, create inside your 'MyDBHandler' a method called something like 'Exists':

 public boolean Exists {

   SQLiteDatabase db = this.getWritableDatabase();

   String Query = "SELECT * FROM TABLE_DETAILS " ;

   Cursor cursor = db.rawQuery(Query,null);
    if(cursor.moveToFirst()){
        Log.i("CHECK", "true");
        return true;
    }
    return false;

}

then inside your activity call Exists something like:

 MyDBHandler db;
 db = new MyDBHandler(getApplicationContext());
 db.getWritableDatabase();

            if ((db.Exists( ))) {
                Toast.makeText(getApplicationContext(), "Please add first your Details", Toast.LENGTH_SHORT).show();

            }else{
            //update your Database
  }

Hope this helps

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Sqlite database updating a row android

From Dev

Adding a new column in SQLite Database

From Dev

SQLite database when updating the app on the store

From Dev

Updating rows in a SQLite database using Python

From Dev

Updating a sqlite3 Database with QSqlQuery

From Dev

Updating a specific row value in sqlite database

From Dev

SQLite Database not updating properly after deleting row

From Dev

Importing large sqlite database to tableview and updating

From Dev

Deleting or updating an entry in an SQLite database in Android

From Dev

Syntax error while updating sqlite database in Android

From Dev

Error creating and adding data to an SQLite database

From Dev

Error creating and adding data to an SQLite database

From Dev

Adding tables to SQLite database using Slick and Scala

From Dev

Android SQLite. Adding a column while updating version

From Dev

updating dataset when adding a new field in database in c#

From Dev

updating dataset when adding a new field in database in c#

From Dev

SQLite Database not updating on updating App from Play Store even after incrementing the database version

From Dev

delete sqlite database when updating new version of application

From Dev

Android Sqlite Database record deleted after updating the apk version

From Dev

Storing, tracking and updating an SQLite database version in C++ application

From Dev

iOS - Keep the old sqlite database while updating to new version

From Dev

Updating an SQLite database via an ODBC linked table in Access

From Dev

Sqlite Update query data in database not updating java gui application

From Dev

Updating sqlite database and using SimpleCursorAdapter causing UI to hang

From Dev

Storing, tracking and updating an SQLite database version in C++ application

From Dev

SQLite database migration to Core Data with updating live version on App Store

From Dev

Updating SQLite3 database in an offline android application later

From Dev

Python sqlite3 'executemany' not successfully updating my database

From Dev

After updating my SQLite database columns via SQLite Manager, why are the changes not reflected in my Android App?

Related Related

  1. 1

    Sqlite database updating a row android

  2. 2

    Adding a new column in SQLite Database

  3. 3

    SQLite database when updating the app on the store

  4. 4

    Updating rows in a SQLite database using Python

  5. 5

    Updating a sqlite3 Database with QSqlQuery

  6. 6

    Updating a specific row value in sqlite database

  7. 7

    SQLite Database not updating properly after deleting row

  8. 8

    Importing large sqlite database to tableview and updating

  9. 9

    Deleting or updating an entry in an SQLite database in Android

  10. 10

    Syntax error while updating sqlite database in Android

  11. 11

    Error creating and adding data to an SQLite database

  12. 12

    Error creating and adding data to an SQLite database

  13. 13

    Adding tables to SQLite database using Slick and Scala

  14. 14

    Android SQLite. Adding a column while updating version

  15. 15

    updating dataset when adding a new field in database in c#

  16. 16

    updating dataset when adding a new field in database in c#

  17. 17

    SQLite Database not updating on updating App from Play Store even after incrementing the database version

  18. 18

    delete sqlite database when updating new version of application

  19. 19

    Android Sqlite Database record deleted after updating the apk version

  20. 20

    Storing, tracking and updating an SQLite database version in C++ application

  21. 21

    iOS - Keep the old sqlite database while updating to new version

  22. 22

    Updating an SQLite database via an ODBC linked table in Access

  23. 23

    Sqlite Update query data in database not updating java gui application

  24. 24

    Updating sqlite database and using SimpleCursorAdapter causing UI to hang

  25. 25

    Storing, tracking and updating an SQLite database version in C++ application

  26. 26

    SQLite database migration to Core Data with updating live version on App Store

  27. 27

    Updating SQLite3 database in an offline android application later

  28. 28

    Python sqlite3 'executemany' not successfully updating my database

  29. 29

    After updating my SQLite database columns via SQLite Manager, why are the changes not reflected in my Android App?

HotTag

Archive