android database sqlite rawquery, no content - database

I have an Activity called Wartung. In this Activity are textfields which should be auto filled by database content. Writing to the DB table works but reading from it doesn't.
I didn't get any errors or warnings in LogCat.
In the method Wartung.getWartungsDaten(String serienNr) I call the method of the helper class DBController.getLetzterWartungsDaten(String serienNr). The last one does a rawquery to the DB.
To test which parts of the code are executed, ich make a toast("1") which is showed, also toast("2") , but toast("3") isn't. The problem must be in the line "Cursor wartungsCursor = this.dbHelper.getLetzteWartungsDaten(serienNr);" or in the helper class respectively in the method getLetzteWartungsDaten().
Here is my class Wartung:
public class Wartung extends Activity {
private DBController dbHelper;
private SQLiteDatabase db;
private EditText serienNr;
private EditText datum;
private EditText zeit;
private EditText benutzer;
private EditText beschreibung;
private EditText statusAktuell;
private Spinner statusNeu;
private Button buttonAendern;
private LinearLayout layoutStatusAktuell;
private LinearLayout layoutStatusNeu;
private String sSerienNr;
private String sArtikelId;
private String sDatum;
private String sZeit;
private String sBenutzer;
private String sStatus;
private String sBeschreibung;
private List<String> statusListe;
private List<String> listeWartungSerienNr;
private List<String> listeWartungDatum;
private List<String> listeWartungZeit;
private List<String> listeWartungBenutzer;
private List<String> listeWartungStatus;
private List<String> listeWartungBeschreibung;
private boolean editModus = false;
private boolean gespeichert = false;
private int statusPosition = -1;
/**
* Initialisierung aller Objekte
*
*/
private void initObjekte() {
this.serienNr = (EditText) this.findViewById(R.id.editText_wartung_content_serienNr);
this.datum = (EditText) this.findViewById(R.id.editText_wartung_content_datum);
this.zeit = (EditText) this.findViewById(R.id.editText_wartung_content_zeit);
this.benutzer = (EditText) this.findViewById(R.id.editText_wartung_content_benutzer);
this.statusAktuell = (EditText) this.findViewById(R.id.editText_wartung_content_aktueller_status);
this.statusNeu = (Spinner) this.findViewById(R.id.spinner_wartung_content_neuer_status);
this.layoutStatusAktuell = (LinearLayout) this.findViewById(R.id.linearLayoutStatusAktuell);
this.layoutStatusNeu = (LinearLayout) this.findViewById(R.id.linearLayoutStatusNeu);
this.listeWartungSerienNr = new ArrayList<String>();
this.listeWartungDatum = new ArrayList<String>();
this.listeWartungZeit = new ArrayList<String>();
this.listeWartungBenutzer = new ArrayList<String>();
this.listeWartungStatus = new ArrayList<String>();
this.listeWartungBeschreibung = new ArrayList<String>();
this.sArtikelId = new String();
this.sDatum = new String();
this.sZeit = new String();
this.sBenutzer = new String();
this.sStatus = new String();
this.sBeschreibung = new String();
this.statusListe = new ArrayList<String>();
setStatusInSpinner();
this.beschreibung = (EditText) this.findViewById(R.id.editTextMultiLine_wartung_content_aenderung);
}
public void toast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
/**
*
* #param serienNr
*/
private void getWartungsDaten(String serienNr) {
this.dbHelper = new DBController(this);
this.db = this.dbHelper.getReadableDatabase();
toast("1");
// Cursor auswerten
try {
toast("2");
Cursor wartungsCursor = dbHelper.getLetzteWartungsDaten(serienNr);
toast("3");
// Daten zerlegen
if (wartungsCursor != null) {
if (wartungsCursor.moveToFirst()) {
do {
this.listeWartungDatum.add(wartungsCursor.getString(wartungsCursor.getColumnIndexOrThrow(DBController.KEY_DATUM)));
this.listeWartungZeit.add(wartungsCursor.getString(wartungsCursor.getColumnIndexOrThrow(DBController.KEY_ZEIT)));
} while (wartungsCursor.moveToNext());
}
}
// String result = "result: " + this.sSerienNr + " " + this.sDatum + " " + this.sZeit + " " + this.sBenutzer + " " + this.sStatus + " " + this.sBeschreibung;
String result = "result: " + this.listeWartungDatum.get(0).toString() + " " + this.listeWartungZeit.get(0).toString();
toast("Erhaltene Daten: " + result);
} catch (Exception e) {
;
} finally {
this.db.close();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_wartung);
this.setupActionBar();
initObjekte();
setObjekteReadable();
// Zu Testzwecken wird immer der erste Artikel aus der Datenbank ausgewählt
getWartungsDaten("SerienNr 0000");
}
}
And here is my Helper class DBController:
public Cursor getLetzteWartungsDaten(String serienNr) {
this.db = this.getReadableDatabase();
// Filter-String um die anhängenden Daten über die SerienNr zu bekommen
String serienNrFilter = "SELECT " +
DBController.TABLE_WARTUNG + "." + DBController.KEY_DATUM + ", " +
DBController.TABLE_WARTUNG + "." + DBController.KEY_ZEIT + ", " +
"FROM " + DBController.TABLE_WARTUNG
"ORDER BY " + DBController.KEY_DATUM + " DESC," + DBController.KEY_ZEIT + " DESC" + ")";
return db.rawQuery(serienNrFilter, /*new String[] { serienNr }*/null);
}
I have some other methods with reading methods but only this one doesn't work and I don't know why.
I hope you can help me.
Thanks!

You have an unnecessary comma:
DBController.KEY_ZEIT + ", " +
"FROM "
i.e. syntax error.

Related

is this code work for Update delete search android studio by Apweslk

create database and other things in dbhelper class
public class DBHandler extends SQLiteOpenHelper{
private static final String TAG =DBHandler.class.getSimpleName();
private static final int VERSION =1;
private static final String DATABASE_NAME = "userDb.db";
private String CREATE_TABLE ="CREATE TABLE " + Users.TABLE_NAME + "("
+ Users._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + Users.USER_NAME + " TEXT,"
+ Users.USER_DOB + " TEXT," + Users.USER_GENDER + " TEXT," + Users.USER_PASSWORD + " TEXT " + ")";
private String DROP_TABLE ="DROP TABLE IF EXISTS " +Users.TABLE_NAME;
public DBHandler(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
}
insert data to database sqlite
//adding users
public boolean addInfo(Users addUser){
boolean result = true;
try {
SQLiteDatabase db =this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Users.USER_NAME,addUser.getUserName());
values.put(Users.USER_DOB,addUser.getDob());
values.put(Users.USER_GENDER,addUser.getGender());
values.put(Users.USER_PASSWORD,addUser.getPassword());
result =db.insert(Users.TABLE_NAME,null,values)>0;
}
catch (Exception ex){
result=false;
ex.getMessage();
}
return result;
}
update method of database.is this possible to do
//updateInfor()
public boolean updateInfor(Users updateUser){
boolean result = true;
try{
SQLiteDatabase db =this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Users.USER_NAME,updateUser.getUserName());
values.put(Users.USER_DOB,updateUser.getDob());
values.put(Users.USER_GENDER,updateUser.getGender());
values.put(Users.USER_PASSWORD,updateUser.getPassword());
//update using user id
String[] hello ={String.valueOf(updateUser.getUserName())};
result =db.update(Users.TABLE_NAME,values,Users.USER_NAME+ "=? ",hello) >0;
}
catch (Exception ex){
result =false;
}
return result;
}
retrieving all data from database`
//retrieve data from database
public List<Users>readAllInfor(){
String[] columns ={Users.USER_NAME,Users.USER_DOB,Users.USER_GENDER,Users.USER_PASSWORD};
List<Users> usersList = new ArrayList<Users>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(Users.TABLE_NAME,columns,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
Users user = new Users();
user.setUserId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Users._ID))));
user.setUserName(cursor.getString(cursor.getColumnIndex(Users.USER_NAME)));
user.setDob(cursor.getString(cursor.getColumnIndex(Users.USER_DOB)));
user.setGender(cursor.getString(cursor.getColumnIndex(Users.USER_GENDER)));
user.setPassword(cursor.getString(cursor.getColumnIndex(Users.USER_PASSWORD)));
usersList.add(user);
}while (cursor.moveToNext());
}
cursor.close();
db.close();
return usersList;
}
retrieving data from database using its own id
//overloading method to retrive by id
public Cursor readAllInfor(String user){
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+UserProfile.Users.table_name+" WHERE "+UserProfile.Users.Column_UserName+" = '"+user+"'",null);
return cursor;
}
delete user from database
public boolean deleteUser(Users user){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(Users.TABLE_NAME,Users._ID + "=?",
new String[]{String.valueOf(user.getUserId())});
db.close();
return true;
}
login part checking user using user name and password
public Users checkUser(String email,String password){
Users users =null;
try {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + Users.TABLE_NAME + " WHERE userName = ? AND userPassword = ?" ,new String[]{email,password} );
if (cursor.moveToFirst()){
users = new Users();
users.setUserId(cursor.getInt(0));
users.setUserName(cursor.getString(1));
users.setDob(cursor.getString(2));
users.setGender(cursor.getString(3));
users.setPassword(cursor.getString(4));
}
}catch (Exception e){
users=null;
}
return users;
}
implimantaion of all methods in db helper
public class ProfileManangment extends AppCompatActivity implements View.OnClickListener{
private final AppCompatActivity activity = ProfileManangment.this;
private RadioGroup groupGender;
private RadioButton radioButton;
private EditText username,password,dob;
private Button update;
private Users users;
private DBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_manangment);
iniViews();
iniObjects();
iniListners();
}
private void iniViews() {
username =findViewById(R.id.regUsername);
password =findViewById(R.id.regPassword);
dob =findViewById(R.id.regDob);
update=findViewById(R.id.btnUpadateReg);
groupGender = findViewById(R.id.radioGroupGender);
}
private void iniObjects() {
users =new Users();
dbHandler =new DBHandler(activity);
}
private void iniListners() {
update.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnUpadateReg : addtoDataBase();
break;
}
}
//get values of readio button
public void radioButtonValue(View v){
int radioId = groupGender.getCheckedRadioButtonId();
radioButton =findViewById(radioId);
}
private void addtoDataBase() {
users.setUserName(username.getText().toString().trim());
users.setDob(dob.getText().toString().trim());
int radioId = groupGender.getCheckedRadioButtonId();
radioButton =findViewById(radioId);
users.setGender(radioButton.getText().toString().trim());
users.setPassword(password.getText().toString().trim());
boolean result =dbHandler.addInfo(users);
if(result){
Toast.makeText(ProfileManangment.this,"SUCCESSFULLY REGISTERED",Toast.LENGTH_LONG).show();
Intent intentEditProfile = new Intent(ProfileManangment.this,EditProfile.class);
startActivity(intentEditProfile);
}
else
Toast.makeText(ProfileManangment.this,"AN ERROR OCCURRED",Toast.LENGTH_LONG).show();
}
}
search is the most important thing .please tell me any body how to use the search .my code is following
/**
* StringBuffer was used in aid of using the AlertDialog.Builder to display all the stuff
* on the screen
*/
public void search(View view) {
User user = db.readAllInfor(ET_username.getText().toString());
if(user == null) {
showStuff("Error", "No Data Found!");
return;
}
StringBuffer buffer = new StringBuffer();
buffer.append("User ID: " + user.getId() + "\n");
buffer.append("Username: " + user.getUsername() + "\n");
buffer.append("Date Of Birth: " + user.getDateOfBirth() + "\n");
buffer.append("Password: " + user.getPassword() + "\n");
buffer.append("Gender: " + user.getGender() + "\n\n");
showStuff("Data", buffer.toString());
}
/**
* This was done in the aid of displaying the stuff on the screen
*/
public void showStuff(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
user class that create getters and setters and table columns
class Users implements BaseColumns{
public static final String TABLE_NAME = "user";
public static final String USER_NAME = "userName";
public static final String USER_PASSWORD = "userPassword";
public static final String USER_DOB = "dob";
public static final String USER_GENDER = "userGender";
private int userId;
private String userName;
private String Password;
private String dob;
private String gender;
public Users(){}
//User profile
public final class UserProfile {
private UserProfile(){}
public static class UserPro implements BaseColumns{
public static final String TABLE_NAME = "UserInfo";
public static final String COLUMN_NAME_USERNAME = "userName";
public static final String COLUMN_NAME_DOB = "dateOfBirth";
public static final String COLUMN_NAME_GENDER = "Gender";
}
}
//DBHelper
public class DBHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "UserInfo.db";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase){
String SQL_CREATE_ENTRIES =
"CREATE TABLE " + UserProfile.UserPro.TABLE_NAME + " (" +
UserProfile.UserPro._ID + " INTEGER PRIMARY KEY," +
UserProfile.UserPro.COLUMN_NAME_USERNAME + " TEXT," +
UserProfile.UserPro.COLUMN_NAME_DOB + " TEXT," +
UserProfile.UserPro.COLUMN_NAME_GENDER + " TEXT)";
sqLiteDatabase.execSQL(SQL_CREATE_ENTRIES);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void addInfo(String username, String password){
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(UserProfile.UserPro.COLUMN_NAME_USERNAME, username);
sqLiteDatabase.insert(UserProfile.UserPro.TABLE_NAME, null, values);
}
public Boolean updateInfo(String username, String newpassword, String newdob, String newgender){
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(UserProfile.UserPro.COLUMN_NAME_USERNAME, username);
values.put(UserProfile.UserPro.COLUMN_NAME_GENDER, newgender);
values.put(UserProfile.UserPro.COLUMN_NAME_DOB, newdob);
String selection = UserProfile.UserPro.COLUMN_NAME_USERNAME + " LIKE ?";
String[] selectionArgs = {username};
int count = sqLiteDatabase.update(
UserProfile.UserPro.TABLE_NAME,
values,
selection,
selectionArgs
);
if(count>=1)
return true;
else
return false;
}
public List readAllInfo(){
SQLiteDatabase sqLiteDatabase = getReadableDatabase();
String[] projection = {
BaseColumns._ID,
UserProfile.UserPro.COLUMN_NAME_USERNAME,
UserProfile.UserPro.COLUMN_NAME_DOB,
UserProfile.UserPro.COLUMN_NAME_GENDER
};
String sortOrder = UserProfile.UserPro.COLUMN_NAME_USERNAME + " ASC";
Cursor cursor = sqLiteDatabase.query(
UserProfile.UserPro.TABLE_NAME,
projection,
null,
null,
null,
null,
sortOrder
);
List users = new ArrayList<>();
List dobs = new ArrayList<>();
List genders = new ArrayList<>();
while (cursor.moveToNext()){
String username = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.UserPro.COLUMN_NAME_USERNAME));
String dob = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.UserPro.COLUMN_NAME_DOB));
String gender = cursor.getString(cursor.getColumnIndexOrThrow(UserProfile.UserPro.COLUMN_NAME_GENDER));
users.add(username);
dobs.add(dob);
genders.add(gender);
}
cursor.close();
return users;
}
public Cursor readAllInfo(String username){
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
String selection = UserProfile.UserPro.COLUMN_NAME_USERNAME + " = ?";
String[] selectionArgs = {username};
Cursor data = sqLiteDatabase.rawQuery("SELECT * FROM " + UserProfile.UserPro.TABLE_NAME + " WHERE " + UserProfile.UserPro.COLUMN_NAME_USERNAME + " = ?", selectionArgs);
return data;
}
public int deleteInfo(String username){
SQLiteDatabase sqLiteDatabase = getWritableDatabase();
String selection = UserProfile.UserPro.COLUMN_NAME_USERNAME + " LIKE ?";
String[] selectionArgs = {username};
int deletedRows = sqLiteDatabase.delete(UserProfile.UserPro.TABLE_NAME, selection, selectionArgs);
return deletedRows;
}
}
//Home activity
public class HomeActivity extends AppCompatActivity {
private final AppCompatActivity activity = HomeActivity.this;
private EditText userName;
private EditText password;
private RadioButton genderMale;
private RadioButton genderFemale;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
userName = findViewById(R.id.UserNameEditText);
password = findViewById(R.id.PasswordEditText);
}
public void onClickRegister(View view){
DBHelper dbHelper = new DBHelper(activity);
dbHelper.addInfo(userName.getText().toString().trim(), password.getText().toString().trim());
Toast.makeText(HomeActivity.this, "User Added", Toast.LENGTH_LONG).show();
Intent intent = new Intent(HomeActivity.this, ProfileManagementActivity.class);
startActivity(intent);
}
}
//Edit Profile
public class EditProfileActivity extends AppCompatActivity {
private final AppCompatActivity activity = EditProfileActivity.this;
private Button deleteButton;
private EditText userName;
private EditText password;
private EditText dob;
private RadioButton genderMale;
private RadioButton genderFemale;
private String gender;
private DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
deleteButton = findViewById(R.id.DeleteButton);
userName = findViewById(R.id.UserNameEditText);
password = findViewById(R.id.PasswordEditText);
dob = findViewById(R.id.DOBEditText);
genderMale = findViewById(R.id.MaleRadioButton);
genderFemale = findViewById(R.id.FemaleRadioButton);
genderMale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onRadioButtonClicked(genderMale);
}
});
genderFemale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onRadioButtonClicked(genderFemale);
}
});
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int rows = dbHelper.deleteInfo(userName.getText().toString().trim());
if(rows>0)
Toast.makeText(EditProfileActivity.this, "Entry Deleted", Toast.LENGTH_LONG).show();
else
Toast.makeText(EditProfileActivity.this, "Delete Failed", Toast.LENGTH_LONG).show();
}
});
dbHelper = new DBHelper(activity);
}
public void ReadAllInfo(View view){
Cursor data = dbHelper.readAllInfo(userName.getText().toString());
if(data.getCount() == 0){
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while (data.moveToNext()){
buffer.append("ID : " + data.getString(0) + "\n");
buffer.append("Username : " + data.getString(1) + "\n");
buffer.append("Date of Birth : " + data.getString(2) + "\n");
buffer.append("Gender : " + data.getString(3) + "\n");
}
showMessage("User Details", buffer.toString());
}
public void showMessage(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void onClickEdit(View view){
boolean success = dbHelper.updateInfo(userName.getText().toString(), password.getText().toString(), dob.getText().toString(), gender);
Toast.makeText(EditProfileActivity.this, "Info Update Success: " + success, Toast.LENGTH_LONG).show();
}
public void onRadioButtonClicked(View view){
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()){
case R.id.MaleRadioButton:
if (checked)
gender = "Male";
break;
case R.id.FemaleRadioButton:
if (checked)
gender = "Female";
break;
}
}
}
//profile Manager
public class ProfileManagementActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_management);
}
public void onClickUpdateProfile(View view){
Intent intent = new Intent(ProfileManagementActivity.this, EditProfileActivity.class);
startActivity(intent);
}
}
//DBHelper class
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "UserInformation.db";
public DBHelper(Context context){
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_ENTRIES = "CREATE TABLE "
+ UserProfile.Users.TABLE_NAME + " ("
+ UserProfile.Users._ID + "INTEGER PRIMARY KEY AUTOINCREMENT,"
+ UserProfile.Users.COLUMN_NAME_USERNAME + "TEXT,"
+ UserProfile.Users.COLUMN_NAME_PASSWORD + "TEXT,"
+ UserProfile.Users.COLUMN_NAME_DATEOFBIRTH + "TEXT,"
+ UserProfile.Users.COLUMN_NAME_GENDER + "TEXT)";
db.execSQL(SQL_CREATE_ENTRIES);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("drop table if exists " + UserProfile.Users.TABLE_NAME);
}
public boolean addInfo(String username, String password, String dob, String gender){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(UserProfile.Users.COLUMN_NAME_USERNAME, username);
values.put(UserProfile.Users.COLUMN_NAME_PASSWORD, password);
values.put(UserProfile.Users.COLUMN_NAME_DATEOFBIRTH, dob);
values.put(UserProfile.Users.COLUMN_NAME_GENDER, gender);
int i = (int) db.insert(UserProfile.Users.TABLE_NAME, null, values);
if(i > 0)
return true;
else
return false;
}
public boolean updateInfor(String username, String password, String dob, String gender){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(UserProfile.Users.COLUMN_NAME_USERNAME, username);
values.put(UserProfile.Users.COLUMN_NAME_PASSWORD, password);
values.put(UserProfile.Users.COLUMN_NAME_DATEOFBIRTH, dob);
values.put(UserProfile.Users.COLUMN_NAME_GENDER, gender);
String selection = UserProfile.Users.COLUMN_NAME_USERNAME + " LIKE ?";
String[] selectionArgs = { username };
int i = db.update(
UserProfile.Users.TABLE_NAME,
values,
selection,
selectionArgs
);
if(i > 0)
return true;
else
return false;
}
public Cursor readAllInfor(){
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("select * from " + UserProfile.Users.TABLE_NAME + "",null);
return cursor;
}
public Cursor readAllInfor(String username){
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("select * from " + UserProfile.Users.TABLE_NAME + "where " + UserProfile.Users.COLUMN_NAME_USERNAME+"=\""+username+"\"", null);
return cursor;
}
public boolean deleteInfo(String username){
SQLiteDatabase db = getWritableDatabase();
String selection = UserProfile.Users.COLUMN_NAME_USERNAME + " LIKE ?";
String[] selectionArgs = { username };
int i = db.delete(
UserProfile.Users.TABLE_NAME,
selection,
selectionArgs
);
if(i > 0)
return true;
else
return false;
}
}
//Edit Profile class
public class EditProfileActivity extends AppCompatActivity {
private EditText username, password, dob;
private RadioGroup gender;
private RadioButton male, female;
private Button edit, delete, search;
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
username = (EditText) findViewById(R.id.epusernameedittext);
dob = (EditText) findViewById(R.id.epdateofbirthedittext);
password = (EditText) findViewById(R.id.eppasswordedittext);
gender = (RadioGroup) findViewById(R.id.epagender);
male = (RadioButton) findViewById(R.id.epmale);
female = (RadioButton) findViewById(R.id.epfemale);
edit = (Button) findViewById(R.id.epedit);
delete = (Button) findViewById(R.id.epdelete);
search = (Button) findViewById(R.id.epsearch);
final String radiobuttonid = String.valueOf(gender.getCheckedRadioButtonId());
db = new DBHelper(this);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor cursor = db.readAllInfor(username.getText().toString());
int i = cursor.getCount();
if(i <= 0){
Toast.makeText(EditProfileActivity.this, "User not found", Toast.LENGTH_LONG).show();
}
while (cursor.moveToNext()){
dob.setText(cursor.getString(2));
if(cursor.getString(3).toString().matches("Male")){
male.setChecked(true);
}
else{
female.setChecked(true);
}
password.setText(cursor.getString(4));
}
}
});
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean isInserted = db.updateInfor(
username.getText().toString(),
dob.getText().toString(),
password.getText().toString(),
radiobuttonid
);
if(isInserted == true)
Toast.makeText(EditProfileActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(EditProfileActivity.this, "DAta not Added", Toast.LENGTH_LONG).show();
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean isInserted = db.deleteInfo(
username.getText().toString()
);
if(isInserted == true)
Toast.makeText(EditProfileActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(EditProfileActivity.this, "DAta not Added", Toast.LENGTH_LONG).show();
}
});
db.close();
}
}
//Home Activity
public class HomeActivity extends AppCompatActivity {
private final AppCompatActivity activity = HomeActivity.this;
private EditText username, password;
private RadioButton male, female;
Button login, register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
username = (EditText) findViewById(R.id.usernameedittext);
password = (EditText) findViewById(R.id.passwordedittext);
register = (Button) findViewById(R.id.register);
login = (Button) findViewById(R.id.login);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
registerClick();
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loginClick();
}
});
}
private void loginClick() {
Intent intent = new Intent(HomeActivity.this, EditProfileActivity.class);
startActivity(intent);
}
private void registerClick() {
Intent intent = new Intent(HomeActivity.this, ProfileManagementActivity.class);
startActivity(intent);
}
}
//profile management
public class ProfileManagementActivity extends AppCompatActivity {
private EditText username, password, dob;
private Button register;
private RadioGroup gender;
DBHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_management);
username = (EditText) findViewById(R.id.prusernameedittext);
dob = (EditText) findViewById(R.id.prdateofbirthedittext);
password = (EditText) findViewById(R.id.prpasswordedittext);
register = (Button) findViewById(R.id.prupdate);
gender = (RadioGroup) findViewById(R.id.pragender);
final String radiobuttonid = String.valueOf(gender.getCheckedRadioButtonId());
db = new DBHelper(this);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean isInserted = db.addInfo(
username.getText().toString(),
password.getText().toString(),
dob.getText().toString(),
radiobuttonid
);
if(isInserted == true)
Toast.makeText(ProfileManagementActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(ProfileManagementActivity.this, "DAta not Added", Toast.LENGTH_LONG).show();
}
});
db.close();
}
}
//user profile
public final class UserProfile {
private UserProfile(){}
public static class Users implements BaseColumns{
public static final String TABLE_NAME = "Users";
public static final String COLUMN_NAME_USERNAME = "username";
public static final String COLUMN_NAME_PASSWORD = "password";
public static final String COLUMN_NAME_DATEOFBIRTH = "date_of_birth";
public static final String COLUMN_NAME_GENDER = "gender";
}
}

E/SQLiteLog﹕ (1) table Users_Table has no column named Monday_Calories

Im doing a database which will store user data, username password age gender height email and weight are inputed by the user and the values for the other columns are left as 0.0. when i debug the app i get the following error
E/SQLiteLog﹕ (1) table Users_Table has no column named Monday_Calories
The Error is from the User table, the Product table has not been called yet.
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
//DATABASE VERSION
private static int DATABASE_VERSION = 1;
//DATABASE NAME
private static final String DATABASE_NAME = "AppDatabase";
//TABLE NAMES
private static final String TABLE_USERS = "Users_Table";
private static final String TABLE_PRODUCTS = "Products_Table";
//COMMON COLUMN NAMES
private static final String KEY_USER_ID = "User_ID";
private static final String KEY_PRODUCT_ID = "Product_ID";
//USER TABLE
private static final String KEY_USERNAME = "Username";
private static final String KEY_PASSWORD = "Password";
private static final String KEY_AGE = "Age";
private static final String KEY_EMAIL = "Email";
private static final String KEY_GENDER = "Gender";
private static final String KEY_HEIGHT = "Height";
private static final String KEY_CURRENT_WEIGHT = "Current_Weight";
private static final String KEY_START_WEIGHT = "Start_Weight";
private static final String KEY_WEIGHT_CHANGE = "Weight_Change";
private static final String KEY_BMI = "BMI";
private static final String KEY_BMR = "BMR";
private static final String KEY_MON_CAL = "Monday_Calories";
private static final String KEY_TUES_CAL = "Tuesday_Calories";
private static final String KEY_WED_CAL = "Wednesday_Calories";
private static final String KEY_THUR_CAL = "Thursday_Calories";
private static final String KEY_FRI_CAL = "Friday_Calories";
private static final String KEY_SAT_CAL = "Saturday_Calories";
private static final String KEY_SUN_CAL = "Sunday_Calories";
//PRODUCT TABLE
private static final String KEY_ITEMNAME = "Item_name";
private static final String KEY_ITEMCALORIES = "Item_Calories";
//
private static final String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USERS + "( "
+ KEY_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_USERNAME + " TEXT, "
+ KEY_PASSWORD + " TEXT, "
+ KEY_AGE + " INTEGER, "
+ KEY_EMAIL + " TEXT, "
+ KEY_GENDER + " TEXT, "
+ KEY_HEIGHT + " DOUBLE, "
+ KEY_START_WEIGHT + " DOUBLE, "
+ KEY_CURRENT_WEIGHT + " DOUBLE, "
+ KEY_WEIGHT_CHANGE + " DOUBLE, "
+ KEY_BMI + " DOUBLE, "
+ KEY_BMR + " DOUBLE, "
+ KEY_MON_CAL + "DOUBLE, "
+ KEY_TUES_CAL + " DOUBLE, "
+ KEY_WED_CAL + " DOUBLE, "
+ KEY_THUR_CAL + " DOUBLE, "
+ KEY_FRI_CAL + " DOUBLE, "
+ KEY_SAT_CAL + " DOUBLE, "
+ KEY_SUN_CAL + " DOUBLE ); ";
private static final String CREATE_PRODUCT_TABLE = "CREATE TABLE " + TABLE_PRODUCTS + "( " + KEY_PRODUCT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ KEY_ITEMNAME + " TEXT, "
+ KEY_ITEMCALORIES + " DOUBLE );";
public DatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db){
db.execSQL(CREATE_USER_TABLE);
db.execSQL(CREATE_PRODUCT_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
DATABASE_VERSION = 2;
db.execSQL("DROP TABLE IF IT EXISTS " + TABLE_USERS);
db.execSQL("DROP TABLE IF IT EXISTS " + TABLE_PRODUCTS);
onCreate(db);
}
//CRUD OPERATIONS
public Users getUser(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_USERS,
new String[]{ KEY_USER_ID, KEY_USERNAME, KEY_PASSWORD, KEY_AGE,
KEY_EMAIL, KEY_GENDER, KEY_HEIGHT, KEY_START_WEIGHT,
KEY_CURRENT_WEIGHT, KEY_WEIGHT_CHANGE, KEY_BMI, KEY_BMR},
KEY_USER_ID + "=?",
new String[] {String.valueOf(id)}, null, null, null, null);
if (cursor!= null)
cursor.moveToFirst();
Users users = new Users(Integer.parseInt(cursor.getString(0)), cursor.getString(1),
cursor.getString(2), cursor.getInt(3), cursor.getString(4), cursor.getString(5),
cursor.getDouble(6), cursor.getDouble(7), cursor.getDouble(8), cursor.getDouble(9),
cursor.getDouble(10), cursor.getDouble(11), cursor.getDouble(12), cursor.getDouble(13),
cursor.getDouble(14), cursor.getDouble(15), cursor.getDouble(16), cursor.getDouble(17), cursor.getDouble(18) );
return users;
}
public void addUser(Users users){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USERNAME, users.get_username());
values.put(KEY_PASSWORD, users.get_password());
values.put(KEY_AGE, users.get_age());
values.put(KEY_EMAIL, users.get_email());
values.put(KEY_GENDER, users.get_gender());
values.put(KEY_HEIGHT, users.get_height());
values.put(KEY_START_WEIGHT, users.get_startWeight());
values.put(KEY_CURRENT_WEIGHT, users.get_currentWeight());
values.put(KEY_WEIGHT_CHANGE, users.get_weightChange());
values.put(KEY_BMI, users.get_BMI());
values.put(KEY_BMR, users.get_BMR());
values.put(KEY_MON_CAL, users.get_monCal());
values.put(KEY_TUES_CAL, users.get_tuesCal());
values.put(KEY_WED_CAL, users.get_wedCal());
values.put(KEY_THUR_CAL, users.get_thurCal());
values.put(KEY_FRI_CAL, users.get_friCal());
values.put(KEY_SAT_CAL, users.get_satCal());
values.put(KEY_SUN_CAL, users.get_sunCal());
db.insert(TABLE_USERS, null, values);
db.close();
}
public int getUserCount(){
String countQuery = "SELECT * FROM " + TABLE_USERS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}
public int updateUser(Users users){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_USERNAME, users.get_username());
values.put(KEY_PASSWORD, users.get_password());
values.put(KEY_AGE, users.get_age());
values.put(KEY_EMAIL, users.get_email());
values.put(KEY_GENDER, users.get_gender());
values.put(KEY_HEIGHT, users.get_height());
values.put(KEY_START_WEIGHT, users.get_startWeight());
values.put(KEY_CURRENT_WEIGHT, users.get_currentWeight());
values.put(KEY_WEIGHT_CHANGE, users.get_weightChange());
values.put(KEY_BMI, users.get_BMI());
values.put(KEY_BMR, users.get_BMR());
values.put(KEY_MON_CAL, users.get_monCal());
values.put(KEY_TUES_CAL, users.get_tuesCal());
values.put(KEY_WED_CAL, users.get_wedCal());
values.put(KEY_THUR_CAL, users.get_thurCal());
values.put(KEY_FRI_CAL, users.get_friCal());
values.put(KEY_SAT_CAL, users.get_satCal());
values.put(KEY_SUN_CAL, users.get_sunCal());
return db.update(TABLE_USERS, values, KEY_USER_ID + " = ?",
new String[]{String.valueOf(users.get_id())});
}
public List<Users> getallUsers(){
List<Users> usersList = new ArrayList<Users>();
String selectQuery = "SELECT * FROM " + TABLE_USERS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()){
do {
Users users = new Users();
users.set_id(Integer.parseInt(cursor.getString(0)));
users.set_username(cursor.getString(1));
users.set_password(cursor.getString(2));
users.set_age(cursor.getInt(3));
users.set_email(cursor.getString(4));
users.set_gender(cursor.getString(5));
users.set_height(cursor.getDouble(6));
users.set_startWeight(cursor.getDouble(7));
users.set_currentWeight(cursor.getDouble(8));
users.set_weightChange();
users.set_BMI(cursor.getDouble(10));
users.set_BMR(cursor.getDouble(11));
users.set_monCal(cursor.getDouble(12));
users.set_tuesCal(cursor.getDouble(13));
users.set_wedCal(cursor.getDouble(14));
users.set_thurCal(cursor.getDouble(15));
users.set_friCal(cursor.getDouble(16));
users.set_satCal(cursor.getDouble(17));
users.set_sunCal(cursor.getDouble(18));
usersList.add(users);
}while (cursor.moveToNext());
}
return usersList;
}
}
Actually your column is named Monday_CaloriesDOUBLE, because you miss a space here
+ KEY_MON_CAL + "DOUBLE, "
It must be
+ KEY_MON_CAL + " DOUBLE, "

How do I make each listview item display different data?

I am creating an application for organizing school courses and entering assignments for each class. When a course in the listview is clicked on, another layout for that specific classes assignments should be displayed. How would I save assignments for each course so that when another course is selected, that specific courses assignments are displayed using databases like below?
Thanks in advance.
public class CourseTable {
// Database table
public static final String TABLE_COURSE = "course";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAMECOURSE = "namecourse";
public static final String COLUMN_DAYOFCOURSE = "dayofcourse";
public static final String COLUMN_TIMEOFCOURSE = "timeofcourse";
// Database creation SQL statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_COURSE
+ "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_NAMECOURSE + " text not null, "
+ COLUMN_DAYOFCOURSE + " text not null,"
+ COLUMN_TIMEOFCOURSE + " text not null,"
+ ");";
public static void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
public static void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.w(CourseTable.class.getName(), "Upgrading database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS " + TABLE_COURSE);
onCreate(database);
}
ContentProvider:
public class CourseContentProvider extends ContentProvider {
// database
private CourseDBHelper database;
// Used for the UriMacher
private static final int COURSES = 10;
private static final int COURSE_ID = 20;
private static final String AUTHORITY = "entcproject.organizer.tamu.main.contentprovider";
private static final String BASE_PATH = "courses";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH);
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
+ "/courses";
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
+ "/course";
private static final UriMatcher sURIMatcher = new UriMatcher(
UriMatcher.NO_MATCH);
static {
sURIMatcher.addURI(AUTHORITY, BASE_PATH, COURSES);
sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", COURSE_ID);
}
#Override
public boolean onCreate() {
database = new CourseDBHelper(getContext());
return false;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
checkColumns(projection);
queryBuilder.setTables(CourseTable.TABLE_COURSE);
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case COURSES:
break;
case COURSE_ID:
queryBuilder.appendWhere(CourseTable.COLUMN_ID + "="
+ uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
SQLiteDatabase db2 = database.getWritableDatabase();
Cursor cursor = queryBuilder.query(db2, projection, selection,
selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = database.getWritableDatabase();
int rowsDeleted = 0;
long id = 0;
switch (uriType) {
case COURSES:
id = sqlDB.insert(CourseTable.TABLE_COURSE, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(BASE_PATH + "/" + id);
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = database.getWritableDatabase();
int rowsUpdated = 0;
switch (uriType) {
case COURSES:
rowsUpdated = sqlDB.update(CourseTable.TABLE_COURSE,
values,
selection,
selectionArgs);
break;
case COURSE_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = sqlDB.update(CourseTable.TABLE_COURSE,
values,
CourseTable.COLUMN_ID + "=" + id,
null);
} else {
rowsUpdated = sqlDB.update(CourseTable.TABLE_COURSE,
values,
CourseTable.COLUMN_ID + "=" + id
+ " and "
+ selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
private void checkColumns(String[] projection) {
String[] available = { CourseTable.COLUMN_NAMECOURSE,
CourseTable.COLUMN_DAYOFCOURSE, CourseTable.COLUMN_TIMEOFCOURSE,
CourseTable.COLUMN_ID };
if (projection != null) {
HashSet<String> requestedColumns = new HashSet<String>(
Arrays.asList(projection));
HashSet<String> availableColumns = new HashSet<String>(
Arrays.asList(available));
// Check if all columns which are requested are available
if (!availableColumns.containsAll(requestedColumns)) {
throw new IllegalArgumentException(
"Unknown columns in projection");
}
}
}
}

Database Updating

I have a web app, where when a page loads, the address details are extracted from the database and displayed in the corresponding text-fields. However when I try to update and save the data, the data doesn't get updated.
However the same works fine when the extraction of data happens through the click of a button.
here's the code :
public partial class Address : System.Web.UI.Page
{
string global;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
global = Session["ID"].ToString();
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Server = INLD50045747A\\SQLEXPRESS; Database = MyDatabase;User ID = sa; Password = Welcome1; Trusted_Connection = False;");
//SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT PermanentAdd,PermanentAdd2, HomePlace, HomeState, HomePin FROM EMPLOYEE_FULLADDRESS_TABLE WHERE EmployeeID = '" + global + "'", con);
SqlDataReader x = cmd.ExecuteReader();
while (x.Read())
{
TextBox1.Text = (string)x["PermanentAdd"];
TextBox1.Enabled = false;
TextBox5.Text = (string)x["PermanentAdd2"];
TextBox5.Enabled = false;
TextBox2.Text = (string)x["HomePlace"];
TextBox2.Enabled = false;
TextBox3.Text = (string)x["HomeState"];
TextBox3.Enabled = false;
State.Items.FindByText(State.SelectedItem.Text).Selected = false;
State.Items.FindByText(TextBox3.Text).Selected = true;
State.Enabled = false;
TextBox4.Text = (string)x["HomePin"];
TextBox4.Enabled = false;
}
x.Close();
con.Close();
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
try
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Server = INLD50045747A\\SQLEXPRESS; Database = MyDatabase;User ID = sa; Password = Welcome1; Trusted_Connection = False;");
//System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True;User Instance=True");
con.Open();
// global = Session["ID"].ToString();
//string insert = "UPDATE EMPLOYEE_FULLADDRESS_TABLE SET PermanentAdd = #PermanentAdd, PermanentAdd2 = #PermanentAdd2, HomePlace = #HomePlace, HomeState= #HomeState, HomePin= #HomePin where EmployeeID = '" + global + "'";
SqlCommand cmd1 = new SqlCommand("UPDATE EMPLOYEE_FULLADDRESS_TABLE SET PermanentAdd = #PermanentAdd, PermanentAdd2 = #PermanentAdd2, HomePlace = #HomePlace, HomeState= #HomeState, HomePin= #HomePin where EmployeeID = '" + global + "'", con);
cmd1.Parameters.AddWithValue("#PermanentAdd", TextBox1.Text);
cmd1.Parameters.AddWithValue("#PermanentAdd2", TextBox5.Text);
cmd1.Parameters.AddWithValue("#HomePlace", TextBox2.Text);
if (State.SelectedItem.Text == "--Select--")
{
State.SelectedItem.Text = TextBox3.Text;
}
cmd1.Parameters.AddWithValue("#HomeState", State.SelectedItem.Text);
cmd1.Parameters.AddWithValue("#HomePin", TextBox4.Text);
cmd1.ExecuteNonQuery();
con.Close();
lblmsg.Text = "DATA Updated Successfully";
lblmsg.ForeColor = System.Drawing.Color.Green;
}
catch (Exception exp)
{
lblmsg.Text = exp.Message;
lblmsg.ForeColor = System.Drawing.Color.Red;
}
}
// static int count = 0;
protected void EditButton_Click(object sender, EventArgs e)
{
TextBox1.Enabled = true;
TextBox2.Enabled = true;
//TextBox3.Enabled = true;
TextBox4.Enabled = true;
TextBox5.Enabled = true;
State.Enabled = true;
}
please help.
I think you have commented out your global / employeeid assignment?
// global = Session["ID"].ToString();
You should also change this to a parameter in your SQL.

Android: database reading problem throws exception

i am having this problem with the android database. I adopted the DBAdapter file the NotepadAdv3 example from the google android page.
DBAdapter.java
public class DBAdapter {
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "PasswordDb";
private static final String DATABASE_TABLE = "myuserdata";
private static final String DATABASE_USERKEY = "myuserkey";
private static final int DATABASE_VERSION = 2;
public static final String KEY_USERKEY = "userkey";
public static final String KEY_TITLE = "title";
public static final String KEY_DATA = "data";
public static final String KEY_ROWID = "_id";
private final Context mContext;
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DB_CREATE_KEY =
"create table " + DATABASE_USERKEY
+ " ("
+ "userkey text not null"
+");";
private static final String DB_CREATE_DATA =
"create table " + DATABASE_TABLE
+ " ("
+ "_id integer primary key autoincrement, "
+ "title text not null"
+ "data text"
+");";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DB_CREATE_KEY);
db.execSQL(DB_CREATE_DATA);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS myuserkey");
db.execSQL("DROP TABLE IF EXISTS myuserdata");
onCreate(db);
}
}
public DBAdapter(Context ctx)
{
this.mContext = ctx;
}
public DBAdapter Open() throws SQLException{
try {
mDbHelper = new DatabaseHelper(mContext);
}
catch(Exception e){
Log.e(TAG, e.toString());
}
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close(){
mDbHelper.close();
}
public Long storeKey(String userKey){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_USERKEY, userKey);
try {
mDb.delete(DATABASE_USERKEY, "1=1", null);
}
catch(Exception e)
{
Log.e(TAG, e.toString());
}
return mDb.insert(DATABASE_USERKEY, null, initialValues);
}
public String retrieveKey() {
final Cursor c;
try {
c = mDb.query(DATABASE_USERKEY, new String[] {
KEY_USERKEY},
null,
null,
null,
null,
null);
}catch(Exception e){
Log.e(TAG, e.toString());
return "";
}
if(c.moveToFirst()){
return c.getString(0);
}
else{
Log.d(TAG, "UserKey Empty");
}
return "";
}
//not including any function related to "myuserdata" table
}
Class1.java
{
mUserKey = mDbHelper.retrieveKey();
mDbHelper.storeKey(Key);
}
the error that i am receiving is from Log.e(TAG, e.toString()) in the methods retrieveKey() and storeKey()
"no such table: myuserkey: , while compiling: SELECT userkey FROM myuserkey"
Did you pop the DB version so onUpgrade fires? You're at version 2 in the example above but if you changed the schema since version 2 then you need to pop the version again.
i think you are not mention your provider tag in AndroidManifest.xml .Check it.
u have to mention the tag like
<provider android:name=".name of providerclass"
android:authorities="authority path" />

Resources