Unable to update a record in sqlite database - java

I am making this sample app that will insert, update, delete and retrieve data from database. now the problem I am facing is how to update the record. I know I have to pass Id but how.
MainActivity.java :
public class MainActivity extends Activity {
Button btnSubmit, btnUpdate, btnDelete;
EditText UserName, FirstName, LastName, txtPassword;
RunDatabase db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new RunDatabase(this);
UserName = (EditText) findViewById(R.id.User_Name);
FirstName = (EditText) findViewById(R.id.First_Name);
LastName = (EditText) findViewById(R.id.Last_Name);
txtPassword = (EditText) findViewById(R.id.Password);
btnSubmit = (Button) findViewById(R.id.btn_Submit);
btnSubmit.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v) {
addRow();
}
});
btnUpdate = (Button) findViewById(R.id.btn_Update);
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateRow();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void addRow()
{
try
{
db.addRow
(
UserName.getText().toString(),
FirstName.getText().toString(),
LastName.getText().toString(),
txtPassword.getText().toString()
);
// remove all user input from the Activity
emptyFormFields();
}
catch (Exception e)
{
Log.e("Add Error", e.toString());
e.printStackTrace();
}
}
private void updateRow()
{
try
{
db.updateRow
(
UserName.getText().toString(),
FirstName.getText().toString(),
LastName.getText().toString(),
txtPassword.getText().toString()
);
emptyFormFields();
}
catch (Exception e)
{
Log.e("Update Error", e.toString());
e.printStackTrace();
}
}
private void emptyFormFields()
{
User_Id.setText("");
FirstName.setText("");
LastName.setText("");
UserName.setText("");
txtPassword.setText("");
}
}
RunDatabase.java:
public class RunDatabase {
Context context;
private SQLiteDatabase db; // a reference to the database manager class.
private final String DB_NAME = "Records"; // the name of our database
private final int DB_VERSION = 1; // the version of the database
// the names for our database columns
private final String TABLE_NAME = "tblRecords";
private final String TABLE_ROW_ID = "id";
private final String TABLE_ROW_ONE = "UserName";
private final String TABLE_ROW_TWO = "FirstName";
private final String TABLE_ROW_THREE = "LastName";
private final String TABLE_ROW_FOUR = "Password";
// the beginnings our SQLiteOpenHelper class
public void onCreate(SQLiteDatabase db)
{
String newTableQueryString =
"create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null, " +
TABLE_ROW_ONE + " text, " +
TABLE_ROW_TWO + " text, " +
TABLE_ROW_THREE + " text, " +
TABLE_ROW_FOUR + " text" +
");";
System.out.println(newTableQueryString);
// execute the query string to the database.
db.execSQL(newTableQueryString);
}
public RunDatabase(Context context)
{
this.context = context;
// create or open the database
CustomSQLiteOpenHelper helper = new CustomSQLiteOpenHelper(context);
this.db = helper.getWritableDatabase();
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void addRow(String rowStringOne, String rowStringTwo, String rowStringThree, String rowStringFour)
{
// this is a key value pair holder used by android's SQLite functions
ContentValues values = new ContentValues();
values.put(TABLE_ROW_ONE, rowStringOne);
values.put(TABLE_ROW_TWO, rowStringTwo);
values.put(TABLE_ROW_THREE, rowStringThree);
values.put(TABLE_ROW_FOUR, rowStringFour);
try
{
db.insert(TABLE_NAME, null, values);
}
catch(Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace(); // prints the stack trace to the log
}
}
public void updateRow(long rowID, String rowStringOne, String rowStringTwo, String rowStringThree, String rowStringFour)
{
ContentValues values = new ContentValues();
values.put(TABLE_ROW_ONE, rowStringOne);
values.put(TABLE_ROW_TWO, rowStringTwo);
values.put(TABLE_ROW_THREE, rowStringThree);
values.put(TABLE_ROW_FOUR, rowStringFour);
try {db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null);}
catch (Exception e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// NOTHING TO DO HERE. THIS IS THE ORIGINAL DATABASE VERSION.
// OTHERWISE, YOU WOULD SPECIFIY HOW TO UPGRADE THE DATABASE.
}
}
}

1. In your create table String,
String newTableQueryString =
"create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null, " +
TABLE_ROW_ONE + " text, " +
TABLE_ROW_TWO + " text, " +
TABLE_ROW_THREE + " text, " +
TABLE_ROW_FOUR + " text" +
");";
The ROW_ID is an integer, so in your function updateRow(), the data type for parameter of rowID should be integer, which is passed in the "where" clause. So should change
-> public void updateRow(long rowID, String rowStringOne,...
2. To identify the row you have added, you need to have a primary key which you will be able to identify on the basis of the entry.
Auto increment integer is good for ensuring that the database will have a new row each time,
but the primary key you need should be something you will know to differentiate entries.
Can try a derived key which would be another column in your db, to insert the same with adding rows would be like:
String customPrimaryKey="UserName.getText().toString()+FirstName.getText().toString()+txtPassword.getText().toString()";
db.updateRow
(
UserName.getText().toString(),
FirstName.getText().toString(),
LastName.getText().toString(),
txtPassword.getText().toString(),
// add one more value for a particular entry-a primary key for You to identify that row
customPrimaryKey
);
So you have a way to identify which row to update then, and pass the same in the updateRow() parameters for the where clause

You could try like this-
db.update(TABLE_NAME, values, TABLE_ROW_ID + "=?", String[]{rowID});

Related

How to search value in Sqlite database?

I'm developing an app which is used for contacts and for this i used sqlite database to store name and number so i want to filter name and number for searching for which
i tried that query but
it's not working for me
any solution for problem i used like and "=" both?
public boolean onQueryTextChange(String newText) {
try {
final String temp = newText.toLowerCase();
final ArrayList<Map> map1 = new ArrayList();
try {
dbhelper =new FeedReaderDbHelper(getActivity());
SQLiteDatabase db=dbhelper.getReadableDatabase();
String projection[]={FeedReaderContract.FeedEntry.COLUMNS_TITLE,FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE};
Cursor cursor =db.query(FeedReaderContract.FeedEntry.TABLE_NAME,projection ,FeedReaderContract.FeedEntry.COLUMNS_TITLE+"= ?",new String[]{newText},null,null,null);
while(cursor.moveToFirst()){
String name = cursor.getString(cursor.getColumnIndex(FeedReaderContract.FeedEntry.COLUMNS_TITLE));
String number = cursor.getString(cursor.getColumnIndex(FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE));
Map<String, Object> map = new HashMap();
map.put(name, number);
if (name.toLowerCase().contains(temp)) {
map1.add(map);
Phone.this.adapter.Filter(map1);
}
} }
catch(Exception e){
System.out.print(Retriving_list);
}
}catch(Exception e){
Toast.makeText(getActivity(), First_Retrive_Data, Toast.LENGTH_SHORT).show();
}
//DbHelperClass
public class FeedReaderDbHelper extends SQLiteOpenHelper{
public static final int DB_VERSION =1;
public static String getDataBASE_NAME() {
return DataBASE_NAME;
}
public static void setDataBASE_NAME(String dataBASE_NAME) {
DataBASE_NAME = dataBASE_NAME;
}
public static String DataBASE_NAME;
Context context;
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + FeedReaderContract.FeedEntry.TABLE_NAME + "(" +
FeedReaderContract.FeedEntry._ID + "INTEGER PRIMARY KEY," +
FeedReaderContract.FeedEntry.COLUMNS_TITLE + " TEXT ," +
FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE + " TEXT UNIQUE)";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + FeedReaderContract.FeedEntry.TABLE_NAME;
public FeedReaderDbHelper(Context context) {
super(context, FeedReaderDbHelper.getDataBASE_NAME(), null, DB_VERSION);
this.context=context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_CREATE_ENTRIES);
}
void addContactValues(FeedReaderDbHelper dbhelper ,String name ,String number){
SQLiteDatabase db= dbhelper.getWritableDatabase();
ContentValues values =new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMNS_TITLE ,name);
values.put(FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE,number);
long rows= db.insertWithOnConflict(FeedReaderContract.FeedEntry.TABLE_NAME,null,values,SQLiteDatabase.CONFLICT_IGNORE);
if (rows==-1){
// Toast.makeText(context, String.valueOf(rows)+"not interested", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, String.valueOf(rows)+"inserted", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL(SQL_DELETE_ENTRIES);
onCreate(sqLiteDatabase);
}
}
It's not clear what exact do you want, but if you want do get only rows with given values, it should looks like this:
String mSearchString = "what do you want to search";
String selection = setupSelectionString();
cursor = database.query(NoteContract.NoteEntry.NOTES_TABLE_NAME, projection, selection, selectionArgs,
null, null, sortOrder);
private String setupSelectionString() {
String selection = null;
if (mSearchString != null) {
selection = FeedReaderContract.FeedEntry.COLUMNS_TITLE + " LIKE '%"
+ mSearchString + "%'"
+ " OR " + FeedReaderContract.FeedEntry.COLUMN_SUB_TITLE + " LIKE '%"
+ mSearchString + "%'";
}
return selection;
It works in my app

Difficult to store Shared preferences value to SQLIte in Android and having null value stored

I think i ran out from ideas about how to do this. I am building and TODO app with register and login feature. Once a user is logged, can create new todos task in SQLite(for now), later i want to delete and rename todos as well.
This is my DB class with SQliteHelper.
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "UserManager.db";
// User table name
private static final String TABLE_USER = "user";
// User Table Columns names
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_NAME = "user_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_PASSWORD = "user_password";
//Table mToDo task name
private final static String mTODO = "Todos";
//Todos table columns names
private final static String TASK_ID = "task_Id"; //autoincrement
private final static String user_Id = "userId";
private final static String TITLE = "title";
private final static String CONTENT = "content";
// create table sql query
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_USER_NAME + " TEXT,"
+ COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" +
")";
private String CREATE_mTODO_TABLE = "CREATE TABLE " + mTODO + "("
+ TASK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + user_Id + " TEXT NOT NULL,"
+ TITLE + " TEXT," + CONTENT + " TEXT" + ")";
// drop table sql query
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// this.ctx = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
db.execSQL(CREATE_mTODO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop User Table if exist
db.execSQL(DROP_USER_TABLE);
// Create tables again
onCreate(db);
}
Adding new Task to second table
public void add(ToDo todoTask) {
SQLiteDatabase db = this.getWritableDatabase();
// SharedPreferences sp = PreferenceManager
// .getDefaultSharedPreferences(ctx);
// String d = sp.toString();
ContentValues values = new ContentValues();
values.put(TITLE, todoTask.getTitle());
values.put(CONTENT, todoTask.getContent());
// values.put(user_Id,todoTask.getUserID(d));
// Inserting Row
db.insert(mTODO, null, values);
db.close();
}
ToDo.java
public class ToDo {
private int id;
private String userID;
private String title;
private String content;
public ToDo(String content, int id, String title, String userID) {
this.content = content;
this.id = id;
this.title = title;
this.userID = userID;
}
public ToDo(String content, String title, String userID) {
this.content = content;
this.title = title;
this.userID = userID;
}
public ToDo() {
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getId(String name) {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUserID(String userID) {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
}
Add activity class with inputs and add method
public class addTask extends AppCompatActivity {
private EditText titleUser;
private EditText contentDesc;
private DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_task);
Button btnAdd = (Button) findViewById(R.id.addToDo);
titleUser = (EditText) findViewById(R.id.titleID);
contentDesc = (EditText) findViewById(R.id.contentDescId);
db = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddItem();
}
});
}
private void AddItem() {
ToDo todo = new ToDo();
todo.setTitle(titleUser.getText().toString().trim());
todo.setContent(contentDesc.getText().toString().trim());
db.add(todo);
finish();
}
The current user that is logged, i am putting that user id to Shared preferences
In my second Table i have something like this
task_Id user_id title content
1 null Eat go to Mc
user_id is null here, and i don't know why
i want something like this
task_Id user_id title content
1 2 Eat go to Mc
user_id- should be which user id make the todo
Supposing that you already know how to store and get the userid from the shared preferences.
In your addTask activity, add:
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
userId = sharedPreference.getString("USER_ID",null);
...
}
in the addItem() add:
private void AddItem() {
...
todo.setUserId(userId);
...
}
in the DB add() use this:
public void add(ToDo todoTask) {
...
values.put(USERID, todoTask.getUserId());
...
}
OR:
Another approach is to get the value directly from the DB class if you are sure that you will never insert task for other users.
public void add(ToDo todoTask) {
SQLiteDatabase db = this.getWritableDatabase();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx);
String d = sp.toString();
ContentValues values = new ContentValues();
values.put(TITLE, todoTask.getTitle());
values.put(CONTENT, todoTask.getContent());
values.put(user_Id,todoTask.getUserID(d));
db.insert(mTODO, null, values);
db.close();
}
and in the constructor save the context for further use.
private Context ctx;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.ctx = context;
}
You are creating ToDo Table using user_id. while static String refrenced is userid: hence in database when entered it goes null by default
//Table mToDo task name
private final static String mTODO = "Todos";
//Todos table columns names
private final static String TASK_ID = "task_Id";
private final static String user_Id = "userId"; //<----Wrong Here
private final static String TITLE = "title";
private final static String CONTENT = "content";
private String CREATE_mTODO_TABLE = "CREATE TABLE " + mTODO + "("
+ TASK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + user_Id + " TEXT NOT NULL,"
+ TITLE + " TEXT," + CONTENT + " TEXT" + ")";
Also here is something more for you, Simply you must supply the User Id value to the Field. Below are Some Examples How to do So
private static final String TAG = "DB_HANDLER";
private static final int DATABASE_VERSION = 15;
private static final String DATABASE_NAME = "ElmexContactsManager.db";
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
private static final String TABLE_BIZ_SEGMENT = "BizSegment";
/*01*/private static final String KEY_LOCAL_BIZ_SEGMENT_ID = "LocalBizSegmentId";
/*02*/private static final String KEY_BIZ_SEGMENT_ID = "BizSegmentId";
/*03*/private static final String KEY_BIZ_SEGMENT = "BizSegment";
/*04*/private static final String KEY_ADDED_ON = "AddedOn";
/*05*/private static final String KEY_UPDATED_ON = "UpdatedOn";
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
String CREATE_TABLE_BIZ_SEGMENT = "CREATE TABLE " + TABLE_BIZ_SEGMENT + "("
/*01*/ + KEY_LOCAL_BIZ_SEGMENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
/*02*/ + KEY_BIZ_SEGMENT_ID + " INTEGER,"
/*03*/ + KEY_BIZ_SEGMENT + " TEXT,"
/*04*/ + KEY_ADDED_ON + " TEXT,"
/*05*/ + KEY_UPDATED_ON + " TEXT"
+ ")";
public ContactDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) { try {
sqLiteDatabase.execSQL(CREATE_TABLE_BIZ_SEGMENT);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_TYPE);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_SOURCE);
sqLiteDatabase.execSQL(CREATE_TABLE_CONT_INDUSTRY);
sqLiteDatabase.execSQL(CREATE_TABLE_MARKETING_REGION);
sqLiteDatabase.execSQL(CREATE_TABLE_MARKETING_REGION_BLOCK);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_MASTER);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_DET);
} catch (SQLException e) {
e.printStackTrace();
}
Log.d(TAG, "Table Craeted ");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
// Drop older table if existed
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_BIZ_SEGMENT);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_TYPE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_SOURCE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONT_INDUSTRY);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_MARKETING_REGION);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_MARKETING_REGION_BLOCK);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_MASTER);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_DET);
// Create tables again
onCreate(sqLiteDatabase);
Log.d(TAG, "Table Udgraded to Version :" + i1);
}
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
public void addBizSegment(BizSegment bizSegment) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
ContentValues values = new ContentValues();
values.put(KEY_BIZ_SEGMENT_ID, bizSegment.getBizSegmentId());
values.put(KEY_BIZ_SEGMENT, bizSegment.getBizSegment());
values.put(KEY_ADDED_ON, df.format(bizSegment.getAddedOn()));
values.put(KEY_UPDATED_ON, df.format(bizSegment.getUpdatedOn()));
// Inserting Row
sqLiteDatabase.insert(TABLE_BIZ_SEGMENT, null, values);
//2nd argument is String containing nullColumnHack
sqLiteDatabase.close(); // Closing database connection
}
public void updateBizSegment(BizSegment bizSegment) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
ContentValues values = new ContentValues();
//values.put(KEY_BIZ_SEGMENT_ID, bizSegment.getBizSegmentId());
values.put(KEY_BIZ_SEGMENT, bizSegment.getBizSegment());
values.put(KEY_ADDED_ON, df.format(bizSegment.getAddedOn()));
values.put(KEY_UPDATED_ON, df.format(bizSegment.getUpdatedOn()));
// Inserting Row
sqLiteDatabase.update(TABLE_BIZ_SEGMENT, values, KEY_BIZ_SEGMENT_ID + " = ?", new String[]{String.valueOf(bizSegment.getBizSegmentId())});
//2nd argument is String containing nullColumnHack
sqLiteDatabase.close(); // Closing database connection
}
public List<BizSegment> getBizSegmentAll() {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
List<BizSegment> bizSegmentList = new ArrayList<BizSegment>();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_BIZ_SEGMENT;
Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
try {
BizSegment bizSegment = new BizSegment(cursor.getInt(0),
cursor.getInt(1),
cursor.getString(2),
df.parse(cursor.getString(3)),
df.parse(cursor.getString(4)));
bizSegmentList.add(bizSegment);
} catch (ParseException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
}
cursor.close();
sqLiteDatabase.close();
//2nd argument is String containing nullColumnHack
return bizSegmentList;
}
public void deleteBizSegment(BizSegment bizSegment) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_BIZ_SEGMENT, KEY_BIZ_SEGMENT_ID + " = ?",
new String[]{String.valueOf(bizSegment.getBizSegmentId())});
db.close();
}
Other method is Using Shared Preference suitable for limited Data. It does not provide any relationships. I use this to store basic User related Data. Not for complicated/Relational Large Data. For That Sqlite is preferred.
public class AppPreference {
SharedPreferences pref;
SharedPreferences.Editor edit;
/**
* #param clientMaster object to set preference
* #param context Context of call
*/
public void putPreference(ClientMaster clientMaster, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putInt("ClientId", clientMaster.getClientId());
edit.putString("FirstName", clientMaster.getFirstName());
edit.putString("LastName", clientMaster.getLastName());
edit.putString("Mobile", clientMaster.getMobile());
edit.putInt("PincodeId", clientMaster.getPincodeId());
edit.putString("Email", clientMaster.getEmail());
edit.putString("Password", clientMaster.getPassword());
edit.putString("MembershipCode", clientMaster.getMembershipCode());
edit.putString("MembershipIssueDate", clientMaster.getMembershipIssueDate().toString());
edit.putString("MembershipExpiryDate", clientMaster.getMembershipExpiryDate().toString());
edit.putString("MemberShipUpdatedOn", clientMaster.getMemberShipUpdatedOn().toString());
edit.putString("MemberShipQRCode", clientMaster.getMemberShipQRCode());
edit.putInt("ReferredByTypeID", clientMaster.getReferredByTypeID());
edit.putInt("ReferredByID", clientMaster.getReferredByID());
//edit.putString("LastPasswordUpdatedOn", clientMaster.getLastPasswordUpdatedOn().toString());
edit.putString("TempMembershipCode", clientMaster.getTempMembershipCode());
edit.putString("AddedOn", clientMaster.getAddedOn().toString());
//edit.putString("UpdatedOn", clientMaster.getUpdatedOn().toString());
edit.putBoolean("Login", true);
edit.putBoolean("Skip", false);
edit.commit();
}
/**
*
* #param appLanguage
* #param context
*/
public void putLanguagePreference(String appLanguage, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putString("AppLanguage", appLanguage);
edit.commit();
}
/**
* To clear All Object preference & Login False
*
* #param context Context call
*/
public void clearPreference(Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.clear();
edit.putBoolean("Login", false);
edit.commit();
}
/**
* #param InstanceId Instance Id
* #param context
*/
public void putPreferenceInstance(String InstanceId, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putString("InstanceId", InstanceId);
edit.commit();
}
}

every time creating database after insert a row in android sql

#After insert a row Database is creating again .how can i solve this problem and i can check database is android device monitor
#After insert a row Database is creating again .how can i solve this problem and i can check database is android device monitor
#After insert a row Database is creating again .how can i solve this problem and i can check database is android device monitor
public class DatabaseOperations extends SQLiteOpenHelper {
public static final int Database_version = 2;
public static final String Tag = DatabaseOperations.class.getSimpleName();
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + " INTEGER PRIMARY KEY," +
TableData.TableInfo.USER_PASS +" TEXT "+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ");";
public DatabaseOperations(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null,Database_version);
Log.d("Tag", "Database created");
}
#Override
public void onCreate(SQLiteDatabase sdb) {
sdb.execSQL(SQL_CREATE_ENTRIES);
Log.d("Tag", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void putInformation(DatabaseOperations drop, String name, String pass, String email) {
SQLiteDatabase SQ = drop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_ID, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
cv.put(TableData.TableInfo.USER_EMAIL, email);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
Log.d("Tag", "inert a row");
}
public Cursor getInformation(DatabaseOperations dop) {
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] coloumns = {TableData.TableInfo.USER_ID, TableData.TableInfo.USER_PASS, TableData.TableInfo.USER_EMAIL};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, coloumns, null, null, null, null, null);
return CR;
}
}
RegisterActivity
public class RegisterActivity extends AppCompatActivity {
EditText USER_NAME, USER_PASS, CON_PASS, USER_EMAIL;
String user_name, user_pass, con_pass, user_email;
Button REG;
Context ctx = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
USER_NAME = (EditText) findViewById(R.id.reg_user);
USER_PASS = (EditText) findViewById(R.id.reg_pass);
CON_PASS = (EditText) findViewById(R.id.con_pass);
USER_EMAIL = (EditText) findViewById(R.id.reg_email);
REG = (Button) findViewById(R.id.user_reg);
REG.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
user_name = USER_NAME.getText().toString();
user_pass = USER_PASS.getText().toString();
con_pass = CON_PASS.getText().toString();
user_email = USER_EMAIL.getText().toString();
if (!(user_pass.equals(con_pass))) {
Toast.makeText(getBaseContext(), "Password are not matching", Toast.LENGTH_LONG).show();
USER_NAME.setText("");
USER_PASS.setText("");
CON_PASS.setText("");
USER_EMAIL.setText("");
} else {
DatabaseOperations DB = new DatabaseOperations(ctx);
DB.putInformation(DB, user_name, user_pass, user_email);
Toast.makeText(getBaseContext(), "Registration is suessful", Toast.LENGTH_LONG).show();
finish();
}
}
});
}
}
It is because you are creating table each time you insert a row. To solve this problem you need to change the create table query "CREATE TABLE 'TABLE_NAME' IF NOT EXISTS". The "IF NOT EXISTS" will restrict the system to create the database again if it is created once.
You are calling creating a new Table every time, you create an instance of DatabaseOperations - as your SQL statement 'CREATES'
Modify SQL_CREATE_ENTRIES to something like below
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE IF NOT EXISTS " + TableData.TableInfo.TABLE_NAME + " (" +
TableData.TableInfo.USER_ID + + " integer primary key autoincrement, "+
TableData.TableInfo.USER_PASS +" TEXT "+ "," +
TableData.TableInfo.USER_EMAIL +" TEXT "+ ");";
Edit
1) I've update query to include auto-increment your primary key
2) In your onUpgrade method add the line
db.execSQL("DROP TABLE IF EXISTS " + TableData.TableInfo.TABLE_NAME);
This will delete the table when you change the version of DB.
Next, update the version of by 1, to 3.
Re-run app, it will be rebuild the DB table.

SQLite database is not being created and no error coming

SQLite database is not being created while no error coming.
I have checked the android/data folder trying many things. I am using eclipse. Someone kindly help me and thanks in advance.
My Database.java file is this:
public class Database extends SQLiteOpenHelper {
public static final String DATABASE_NAME="Table.db";
public static final String TABLE_NAME="table_one";
public static final String COL_1="ID";
public static final String COL_2="NAME";
public static final String COL_3="SURNAME";
public static final String COL_4="MARKS";
public Database(Context context) {
super(context, TABLE_NAME, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase arg) {
// TODO Auto-generated method stub
arg.execSQL("create table "+TABLE_NAME+"(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, MARKS INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase arg, int arg1, int arg2) {
// TODO Auto-generated method stub
arg.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(arg);
}
public boolean insert(String name, String sname, String marks)
{
SQLiteDatabase arg=this.getWritableDatabase();
ContentValues content=new ContentValues();
content.put(COL_2, name);
content.put(COL_3, sname);
content.put(COL_4, marks);
long result=arg.insert(TABLE_NAME, null, content);
if(result==-1)
return false;
else
return true;
}
}
MainActivity.java is:
public class MainActivity extends Activity {
Database myDb;
EditText name, sname, marks;
Button add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new Database(this);
name = (EditText) findViewById(R.id.ename);
sname = (EditText) findViewById(R.id.esname);
marks = (EditText) findViewById(R.id.emarks);
add = (Button) findViewById(R.id.button1);
addData();
}
public void addData() {
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
boolean isInserted = myDb.insert(name.getText().toString(), sname.getText().toString(), marks.getText().toString());
if (isInserted == true)
Toast.makeText(MainActivity.this, "Data is inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data is NOT inserted", Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
public Database(Context context)
{
super(context, DATABASE_NAME , null, 1); // Your Mistake
}
Create your table like this :
String CREATE_TABLE = "CREATE TABLE " + GROUP_CHAT_MESSAGE_TABLE_NAME + "("
+ ID + " INTEGER PRIMARY KEY,"
+ NAME + " TEXT,"
+ SURNAME + " TEXT ,"
+ MARKS + " INTEGER" + ")";
db.execSQL(CREATE_TABLE);
Try taking a look here . You should however use a DAO class ; so you can manage information from the database and to it ,through an intermediate object.
Try creating the table like this :
private static final String DATABASE_CREATE = "create table "
+ DATABASE_NAME + "(" + COL_1 +
" integer primary key autoincrement, " +
COL_2 + " text not null, " + COL_3 + " text not null, " + COL_4 + " integer);";

Can't do the insetion in database android

There is a problem with insetion in database. I don't know what to do.
It writes error inserting.
public class MainActivity extends Activity implements OnClickListener {
BaseOpener bo;
private static final String ML = "ML";
Button read, write;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
read = (Button) findViewById(R.id.read);
read.setOnClickListener(this);
write = (Button) findViewById(R.id.write);
write.setOnClickListener(this);
bo = new BaseOpener(this);
Log.i("Ml", "good start");
}
#Override
public void onClick(View v) {
SQLiteDatabase db = bo.getWritableDatabase();
switch (v.getId()) {
case R.id.write:
{
ContentValues cv = new ContentValues();
Log.i("ML", "write");
cv.put("id", 1);
cv.put("name", "Petr");
cv.put("phone", "911");
cv.clear();
db.insert("table1", null, cv);
}
break;
case R.id.read:
{`enter code here`
Log.i("ML", "read");
Cursor c = db.query("table1",null,null,null,null,null,null);
if(c.moveToFirst()){
int idColIndex = c.getColumnIndex("id");
int nameColIndex = c.getColumnIndex("name");
int emailColIndex = c.getColumnIndex("phone");
Log.i("ML",
"ID = " + c.getInt(idColIndex) +
", name = " + c.getString(nameColIndex) +
", phone = " + c.getString(emailColIndex));
}
}
break;
}
db.close();
Log.i("ML", "the base is closed");
}
}
public class BaseOpener extends SQLiteOpenHelper {
public BaseOpener(Context context) {
super(context, "contacts", null, 1);
Log.i("ML", "the base is ready");
}`enter code here`
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table table1 (" + "id integer primary key,"
+ "name String," + "phone String" + ");");
Log.i("ML", "table1 is ready");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
clear()
Removes all values. Read more on ContentValues here
Your table lists id as primary key so you can't insert it twice. I would just comment out the cv.put("id",1) line and let sqlite handle it.
//cv.put("id", 1);
db.execSQL("create table table1 (" + "id integer primary key,"
+ "name String," + "phone String" + ");");
Log.i("ML", "table1 is ready");
Also from your next app on consider naming your id column _id. This will make the table more compatible with cursor adapters and such.
Look at these links they all use _id
cursorAdapter ContentProvider ListView

Categories

Resources