Android SQLiteDatabase insert method only work once - android

I really don't know what is happening to my code. At first, i was able to insert record to my table, then in my second try it just don't run. Please Help. I passed the username through intent which pretty works.
First
String pass = txtpass.getText().toString();
String repass = txtpass2.getText().toString();
String secA = txtans.getText().toString();
String secQ = txtQ.getSelectedItem().toString();
Message.message(this, pass+"and"+repass);
if(pass.equals(repass))
{
long id = mh.insertNewAccount(username, pass, secQ, secA);
if(id < 0)
Message.message(this, "Unsuccesful");
else
{
Message.message(this, "You may now logged in! Enjoy your experience!");
Intent intent = new Intent(this, MainScreen.class);
Bundle bnd=new Bundle();
bnd.putString("username", username);
intent.putExtras(bnd);
txtpass.setText("");
txtpass2.setText("");
txtans.setText("");
startActivity(intent);
}
}
else
{
Message.message_short(this, "Password didn't match!");
txtpass.setText("");
txtpass2.setText("");
}
}
Second - insertNewAccount() Function
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MyHelper.USER_ID, "");
contentValues.put(MyHelper.USER_USERNAME, name);
contentValues.put(MyHelper.USER_PASSWORD, pass);
contentValues.put(MyHelper.USER_SECANS, secA);
contentValues.put(MyHelper.USER_SECQUE, secQ);
long id = db.insert(MyHelper.TABLE_USERS, null, contentValues);
db.close();
return id;

Related

Problem saving regstration form data to sqlite database (App closed immediately)

I'm extremely beginner to android development, I'm making a simple app that has a registration form, but after the fields filled with data and when the save button pressed the app closed immediately.
I've included the code because I don't know where's the faulty part:
public void AddNew(View v)
{
if(Image_path.isEmpty())
{
Toast.makeText(this,"please choose a profile picture",Toast.LENGTH_SHORT).show();
return;
}
EditText ed_full_name = findViewById(R.id.full_name);
EditText ed_mobie = findViewById(R.id.phone);
EditText ed_id_num = findViewById(R.id.id_num);
EditText ed_address = findViewById(R.id.address);
EditText ed_section_id = findViewById(R.id.straction_id);
EditText ed_card_id = findViewById(R.id.card_id);
EditText ed_dis_id = findViewById(R.id.dis_id);
String full_name = ed_full_name.getText().toString();
String mobile = ed_mobie.getText().toString();
String id_num = ed_id_num.getText().toString();
String address = ed_address.getText().toString();
String card_id = ed_card_id.getText().toString();
String section_id = ed_section_id.getText().toString();
String dis_id = ed_dis_id.getText().toString();
if(full_name.isEmpty() || mobile.isEmpty() || id_num.isEmpty() || address.isEmpty() || card_id.isEmpty() || section_id.isEmpty())
{
Toast.makeText(this,"Please fill all fields",Toast.LENGTH_SHORT).show();
return;
}
DBHelper mHelper = new DBHelper(this);
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("full_name", full_name);
values.put("mobile", mobile);
values.put("id_num", id_num);
values.put("address", address);
values.put("section_id", section_id);
values.put("card_id", card_id);
values.put("image_path", Image_path);
values.put("dis_id", dis_id);
db.insertWithOnConflict("Clients",
null,
values,
SQLiteDatabase.CONFLICT_REPLACE);
db.close();
Toast.makeText(this, "Saved successfully! ", Toast.LENGTH_SHORT).show();
finish();
You are calling finish(); on your Activity, that will cause it to close. If it is the only Activity on your App's backstack, the App will also close.

Database is not updating data from one activity to another

I need to pass data from DeleteLayout to update data in historyActivity which will update once I edit the data.It does not throw any error but my data is not updating after editing. What can be done to pass data between activities and update the database.
My updateDatamethod in DatabaseHelper looks like this:
public boolean updateData(String goalDate, String goalWeight, String currentWeight){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String where = "GDATE = ? AND GWEIGHT = ? AND CWEIGHT = ?";
contentValues.put(Col2, goalDate);
contentValues.put(Col3, goalWeight);
contentValues.put(Col4, currentWeight);
db.update(TABLE_NAME, contentValues, where, new String[]{goalDate,goalWeight,currentWeight});
return true;
}
Deletelayout
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.deletelayout);
GoalDate = findViewById(R.id.goalDate2);
CurrentWeight = findViewById(R.id.weighGoal2);
GoalWeight = findViewById(R.id.weightCurrent2);
goalD = findViewById(R.id.goalDateInput);
goalW = findViewById(R.id.goalWeightInput);
currentW = findViewById(R.id.currentWeightInput);
imageView = findViewById(R.id.imageShow);
data = myDB.getListContents();
deleteB = findViewById(R.id.deleteB);
updateB = findViewById(R.id.updateButton);
// Entered information from the user are set to the respective variables.
int numRows = data.getCount();
j = new Intent(DeleteLayout.this, historyActivity.class);
if (numRows == 0) {
Toast.makeText(DeleteLayout.this, "Nothing in the db", Toast.LENGTH_LONG).show();
} else {
int i = 0;
while (data.moveToNext()) {
user = new User(data.getString(1), data.getString(2), data.getString(3), data.getString(4), data.getString(5));
gWt = user.getGoalWeight();
cWt = user.getCurrentWeight();
gDt = user.getGoalDate();
GoalDate.setText(gDt);
GoalWeight.setText(gWt);
CurrentWeight.setText(cWt);
deleteB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDB.deleteContent(GoalDate.getText().toString(), GoalWeight.getText().toString(), CurrentWeight.getText().toString());
startActivity(j);
}
});
updateB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean myUpdate = myDB.updateData(goalD.getText().toString(), goalW.getText().toString(), currentW.getText().toString());
if(myUpdate == true){
Toast.makeText(DeleteLayout.this, "Data updated", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(DeleteLayout.this, "Data not updated", Toast.LENGTH_SHORT).show();
}
startActivity(j);
}
});
}
}
}
Issues
One issue you have is that you are not asking for any changes to be made.
Additionally you are always assuming that a row or rows have always been update, i.e. you are not checking to see if any updates have been performed.
The SQliteDatabase update method returns an int that has the number of rows that have been updated. If none are updated then it will return 0.
Explanation
Consider that goalDate is 2019-01-01 and goalWeight is 100 and currentWeight is 200, then you are saying
update
goalDate to 2019-01-01 and
goalWeight to 100 and
currentWeight to 200
for the row(s) where
goalDate is 2019-01-01 and
goalWeight is 100 and
currentWeight is 200
Fix
Instead of :-
public boolean updateData(String goalDate, String goalWeight, String currentWeight){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String where = "GDATE = ? AND GWEIGHT = ? AND CWEIGHT = ?";
contentValues.put(Col2, goalDate);
contentValues.put(Col3, goalWeight);
contentValues.put(Col4, currentWeight);
db.update(TABLE_NAME, contentValues, where, new String[]{goalDate,goalWeight,currentWeight});
return true;
}
What you want is something along the lines of :-
public boolean updateData(String goalDate, String goalWeight, String currentWeight, String newGoaldate, String newGoalWeight, String newCurrentWeight){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String where = "GDATE = ? AND GWEIGHT = ? AND CWEIGHT = ?";
contentValues.put(Col2, newGoalDate);
contentValues.put(Col3, newGoalWeight);
contentValues.put(Col4, newCurrentWeight);
if (db.update(TABLE_NAME, contentValues, where, new String[]{goalDate,goalWeight,currentWeight}) > 0) {
return true;
}
return false;
}
The first 3 parameters are the original values (used to locate the row to be updated), the second set are the values to be used to update the located row or rows).
Extra
Ideally you should also change :-
String where = "GDATE = ? AND GWEIGHT = ? AND CWEIGHT = ?";
to :-
String where = Col2 + "=? AND " + Col3 + "=? AND " + Col4 +"=?";

how to get the cursor data which is appended to another activity and split the appended data to get the Id of that row

I have a database where i have Unique id, Email id and Password. Im storing using SQlite database. I've to get the cursor which stores the result of the query, i have got the cloumn index of each cloumn, appended it using StringBuffer, but i dont know how to get those values in the other class? please help.
here is my code for Adapter class:
public String getData(String email,String pwd)
{
StringBuffer buffer=new StringBuffer();
SQLiteDatabase db =sciHelper.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT _id FROM " + SciHelper.TABLE_NAME + " WHERE email=? AND password=?", new String[]{email, pwd});
while(cursor.moveToNext())
{
int index1=cursor.getColumnIndex(SciHelper.UID);
int index2=cursor.getColumnIndex(SciHelper.EMAIL);
int index3=cursor.getColumnIndex(SciHelper.PASSWORD);
String cid=cursor.getString(index1);
String mail=cursor.getString(index2);
String mailpass=cursor.getString(index3);
buffer.append(cid +" "+mail+" "+mailpass+"\n");
}
return buffer.toString();
}
code at login class:
public void checkTable(View view) {
email2 = emaillog.getText().toString();
pass2 = passlog.getText().toString();
String data = sciDataBaseAdapter.getData(email2, pass2);
String[] values=data.split("\\");
String cid=values(0);
if (TextUtils.isEmpty(email2)) {
emaillog.setError("Enter Email Id");
passlog.setError("Enter Password");
}
// if (email1 != null) {
Intent intent=new Intent(this,ResultActivity.class);
startActivity(intent);
Message.message(this, "Login succesful");
} else {
Message.message(this, "Invalid username/ or register");
}
}
}
When calling the ResultAcitvity
Intent intent=new Intent(this,ResultActivity.class);
intent.putExtra("key","value");
startActivity(intent);
and on ResultActivity, inside onCreate() method write
Intent intent=getIntent();
String value=intent.getStringExtra("key");
String[] values = value.split(" ");
String cid=values[0];
String mail=values[1];
String mailpass=values[2];
public void checkTable(View view) {
email2 = emaillog.getText().toString();
pass2 = passlog.getText().toString();
String data = sciDataBaseAdapter.getData(email2, pass2);
String[] values=data.split("\\");
String cid=values(0);
if (TextUtils.isEmpty(email2)) {
emaillog.setError("Enter Email Id");
passlog.setError("Enter Password");
}
// if (email1 != null) {
Bundle bundle=new Bundle();
b.putStringArray(some_key, values);
Intent intent=new Intent(this,ResultActivity.class);
intent.putExtra(bundle);
startActivity(intent);
Message.message(this, "Login succesful");
} else {
Message.message(this, "Invalid username/ or register");
}
}
and in your next activity get that using.
Bundle extras = getIntent().getExtras();
String[] some_variable= extras.getString("some_key");

How to add data in android sqlite?

I want to add my new values in the previous one at a specific id, but every time when I want to add it created data on a new id rather than added with the previous one.
Here is the method of my databasehelper class:
public boolean addalldata(String value1, String value2, String value3) {
String previous1 = null,previous2 = null,previous3= null;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String myquery = "SELECT * FROM student_table WHERE id = 1";
Cursor res = db.rawQuery(myquery, null);
while(res.moveToNext()) {
previous1 = res.getString(1);
previous2 = res.getString(2);
previous3 = res.getString(3);
}
contentValues.put(COL_2, value1 + previous1);
contentValues.put(COL_3, value2 + previous2);
contentValues.put(COL_4, value3 + previous3);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;}
here is the method of mainactivity class
private void AddAllData() {
btnaddall.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.addalldata(edit1.getText().toString(),
edit2.getText().toString(),
edit3.getText().toString());
if (isInserted = true)
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Data not Inserted", Toast.LENGTH_LONG).show();
}
}
);
}
try this:
public boolean addalldata(String value1, String value2, String value3) {
String previous1 = "0",previous2 = "0",previous3= "0";
long result = 0;
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String myquery = "SELECT * FROM student_table WHERE id = 1";
Cursor res = db.rawQuery(myquery, null);
if(res.getCount()>0){
res.moveToFirst();
previous1 = res.getString(1);
previous2 = res.getString(2);
previous3 = res.getString(3);
try{
contentValues.put(COL_2, Integer.parseInt(value1) + Integer.parseInt(previous1));
contentValues.put(COL_3, Integer.parseInt(value2) + Integer.parseInt(previous2));
contentValues.put(COL_4, Integer.parseInt(value3) + Integer.parseInt(previous3));
result = db.update(TABLE_NAME, contentValues, "id = ?", new String[]{"1"});
}catch(Exception e){
result = -1;
}
if (result == -1)
return false;
else
return true;
}else{
contentValues.put(COL_2, value1);
contentValues.put(COL_3, value2);
contentValues.put(COL_4, value3);
result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
}
if there is no record in the database then insert a new record using db.insert otherwise update the existing record by using db.update
try res.moveToFirst().This will move your cursor to first position so that furthur checking starts from the first row.

Check Db column data

I want my Onclick method that is used used to insert data into a database to first check if data exist. If there is data, a toast message appears. how can I accomplish this. My OnClick is below. I just it to verify there is a username and password. If there is, the user receives a toast.
#Override
public void onClick (View v) {
rUsername = rName.getText().toString();
rPasscode = rCode.getText().toString();
RegDetails regDetails = new RegDetails();
regDetails.setrName(bundleRegName);
regDetails.setpCode(bundleRegCode);
if(v.getId()==R.id.rtn_button){
finish();
}else if(v.getId()==R.id.reg_button){
insertCredentials(regDetails);
}
}
private void insertCredentials(RegDetails regDetails){
LoginDB androidOpenDBHelper = new LoginDB(this);
SQLiteDatabase sqliteDB = androidOpenDBHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LoginDB.COLUMN_NAME_USERNAME, rUsername);
contentValues.put(LoginDB.COLUMN_NAME_PASSWORD, rPasscode);
long affectedColumnid = sqliteDB.insert(LoginDB.TABLE_NAME_CREDENTIALS, null, contentValues);
Toast.makeText(getApplicationContext(), "Credentials Saved! Please login" + affectedColumnid, Toast.LENGTH_SHORT).show();
sqliteDB.close();
finish();
}
}
The sqliteDB.insert return long value on success and -1 on error. The long value indicates the row number for newly inserted row in db. You can check this return value and display toast accordingly.
Please look at the detailed explanation here, http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#insert(java.lang.String, java.lang.String, android.content.ContentValues)
In short, modify your code to be like this,
private void insertCredentials(RegDetails regDetails){
LoginDB androidOpenDBHelper = new LoginDB(this);
SQLiteDatabase sqliteDB = androidOpenDBHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(LoginDB.COLUMN_NAME_USERNAME, rUsername);
contentValues.put(LoginDB.COLUMN_NAME_PASSWORD, rPasscode);
long affectedColumnid = sqliteDB.insert(LoginDB.TABLE_NAME_CREDENTIALS, null, contentValues);
if(affectedColumnid != -1){
Toast.makeText(getApplicationContext(), "Credentials Saved! Please login" + affectedColumnid, Toast.LENGTH_SHORT).show();
}else{
// Display error dialog or smthg
}
sqliteDB.close();
finish();
}
Read your database . If cursor.getCount() >0 thats mean data exists.
Cursor cursor = getDbEntries();
if( cursor.getCount() > 0 ){
// data exists
}
else{
// data doesnt exist
}

Categories

Resources