Insert data to the sqlite database - android

i am trying to send data to database but i,m getting this error
under this line (db.insertData(fname, lname, pnumber, email, nic)) the error is
insertdata() in databasehelper cannot be applied to fname:java.lang.String fname(android.widget.EditText)
the code is looks like this
` public void onClick(View view) {
if (fname.getText().toString().trim().length() == 0 ||
lname.getText().toString().trim().length() == 0 ||
pnumber.getText().toString().trim().length() == 0 ||
email.getText().toString().trim().length() == 0 ||
nic.getText().toString().trim().length() == 0) {
Toast.makeText(AddEmployee.this, "Complete all fields", Toast.LENGTH_SHORT).show();
} else if (db.insertData(fname, lname, pnumber, email, nic)) {
Toast.makeText(AddEmployee.this, "Employee Register Successfully", Toast.LENGTH_SHORT).show();
fname.setText("");
lname.setText("");
pnumber.setText("");
email.setText("");
nic.setText("");
} else {
Toast.makeText(AddEmployee.this, "Error", Toast.LENGTH_SHORT).show();
}
}`
Database Helper is like this
public boolean insertData(String fname, String lname, Integer pnumber, String email, String nic) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(FNAME, fname);
contentValues.put(LNAME, lname);
contentValues.put(PNUMBER, pnumber);
contentValues.put(EMAIL, email);
contentValues.put(NIC, nic);
long result = db.insert(DB_TABLE, null, contentValues);
return result != -1;
}

As I understand you are passing edittext to DB but you have to pass string
So instead of fname write fname.getText().toString() in your else if and this will solve your problem

Related

How to Pass TABLE ID AUTO_INCREMENT to Another Multiple Table using SQLite in Android

How to pass First Table Id to Second Table for inserting multiple record in Second Table for 1 Employee
For Example in FIRST_TABLE 1 Employee with some Personal details
now in SECOND_TABLE Employee having more data with more rows
for identify i want to pass Table id in Second_table.
Can any one help me,
Thanks in advance..
Here is My Database Code
TABLE_NAME_FARMER_SYNC = FIRST_TABLE
TABLE_NAME_ANIMAL_SYNC = SECOND_TABLE
db.execSQL("create table " + TABLE_NAME_FARMER_SYNC + "(NEW_INSURANCE_ID INTEGER PRIMARY KEY AUTOINCREMENT,INSURANCE_ID TEXT,INSURED_NAME TEXT,BANKHYPO_NAME TEXT,FARMER_NAME TEXT,VILLAGE TEXT,TALUKA TEXT,DISTRICT TEXT,TAGGING_DATE DATE)");
db.execSQL("create table " + TABLE_NAME_ANIMAL_SYNC + "(NEW_ANIMAL_ID INTEGER PRIMARY KEY AUTOINCREMENT,FARMER_ID INT,TAG_NO TEXT,ANIMAL_EAR_POSITION TEXT,ANIMAL_SPECIES TEXT,ANIMAL_BREED TEXT,ANIMAL_BODY_COLOR TEXT,ANIMAL_SHAPE_RIGHT TEXT,ANIMAL_SHAPE_LEFT TEXT,ANIMAL_SWITCH_OF_TAIL TEXT,AGE_YEARS NUMBER,ANIMAL_OTHER_MARKS NUMBER,PRAG_STATUS NUMBER,NUMBER_OF_LACTATION NUMBER,CURRENT_MILK NUMBER,SUM_INSURED NUMBER,TAG_IMAGE BLOB NOT NULL,HEAD_IMAGE BLOB NOT NULL,LEFT_SIDE_IMAGE BLOB NOT NULL,RIGHT_SIDE_IMAGE BLOB NOT NULL,TAIL_IMAGE BLOB NOT NULL,IDPROOF_IMAGE BLOB NOT NULL)");
Here I want to Pass NEW_INSURANCE_ID which is AUTO INCREMENT in SECOND_TABEL As FARMER_ID.
Insert Data in FirstTable
public boolean addFarmerName(String insurance_id, String insurename, String bankhypo, String farmername, String village, String taluka, String district, String tagging_date) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(INSURANCE_ID, insurance_id);
contentValues.put(INSURED_COLUMN, insurename);
contentValues.put(BNAKHYPO_COLUMN, bankhypo);
contentValues.put(FARMERNAME_COLUMN, farmername);
contentValues.put(VILLAGE_COLUMN, village);
contentValues.put(TALUKA_COLUMN, taluka);
contentValues.put(DISTRICT_COLUMN, district);
contentValues.put(TAGGING_DATE_COLUMN, tagging_date);
db.insert(TABLE_NAME_FARMER_SYNC, null, contentValues);
db.close();
return true;
}
Insert Data in Second Table
public boolean addAnimalsName(String tag, long farmer_id, String ear_position, String animal_species, String animal_breeds, String animal_body_color, String shape_right, String shape_left, String tail, String age, String marks_other, String prag, String lactation, String current_milk, String sum, byte[] tag_image, byte[] head_image, byte[] left_image, byte[] right_image, byte[] tail_image, byte[] id_proof_image) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TAG_COLUMN, tag);
contentValues.put(FARMER_ID, farmer_id);
contentValues.put(ANIMAL_EAR_POSITION_COLUMN, ear_position);
contentValues.put(ANIMAL_SPECIES_COLUMN, animal_species);
contentValues.put(ANIMAL_BREED_COLUMN, animal_breeds);
contentValues.put(ANIMAL_BODY_COLOR_COLUMN, animal_body_color);
contentValues.put(ANIMAL_SHAPE_RIGHT_COLUMN, shape_right);
contentValues.put(ANIMAL_SHAPE_LEFT_COLUMN, shape_left);
contentValues.put(ANIMAL_SWITCH_OF_TAIL_COLUMN, tail);
contentValues.put(AGE_COLUMN, age);
contentValues.put(ANIMAL_OTHER_MARKS_COLUMN, marks_other);
contentValues.put(PRAG_STATUS_COLUMN, prag);
contentValues.put(NUMBER_OF_LACTATION_COLUMN, lactation);
contentValues.put(CURRENT_MILK_COLUMN, current_milk);
contentValues.put(SUM_INSURED_COLUMN, sum);
contentValues.put(TAG_IMAGE_COLUMN, tag_image);
contentValues.put(HEAD_IMAGE_COLUMN, head_image);
contentValues.put(LEFT_SIDE_IMAGE_COLUMN, left_image);
contentValues.put(RIGHT_SIDE_IMAGE_COLUMN, right_image);
contentValues.put(TAIL_IMAGE_COLUMN, tail_image);
contentValues.put(IDPROOF_IMAGE_COLUMN, id_proof_image);
db.insert(TABLE_NAME_ANIMAL_SYNC, null, contentValues);
db.close();
return true;
}
First Activity Code
private void addDataInTable() {
boolean insertData = databaseHelper.addFarmerName(id, bank_insured, bank_hypo, editTextFarmerName.getText().toString() + "", editTextVillage.getText().toString() + "", editTextTaluka.getText().toString() + "",
editTextDistrict.getText().toString() + "", editTextTaggingDate.getText().toString() + "");
if (insertData) {
Toast.makeText(context, "Data Save Successfully in SQLite Database", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Data Not Save in SQLite Database", Toast.LENGTH_SHORT).show();
}
}
Second Activity Code
private void addDataInTable(byte[] NewEntryImg1, byte[] NewEntryImg2,
byte[] NewEntryImg3, byte[] NewEntryImg4, byte[] NewEntryImg5,
byte[] NewEntryImg6) {
boolean insertData = databaseHelper.addAnimalsName(tag_no, tag1_id, ear_position, animal_species, animal_breed, body_color, shape_right, shape_left,
tail_switch, age, other_marks, prag_status, lactations, milk_qty, sum_insured
, NewEntryImg1, NewEntryImg2, NewEntryImg3, NewEntryImg4, NewEntryImg5, NewEntryImg6);
if (insertData) {
Toast.makeText(context, "Data Save Successfully in SQLite Database", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Data Not Save in SQLite Database", Toast.LENGTH_SHORT).show();
}
}
public int addFarmerName(String insurance_id, String insurename, String bankhypo,
String farmername, String village, String taluka, String district, String
tagging_date) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(INSURANCE_ID, insurance_id);
contentValues.put(INSURED_COLUMN, insurename);
contentValues.put(BNAKHYPO_COLUMN, bankhypo);
contentValues.put(FARMERNAME_COLUMN, farmername);
contentValues.put(VILLAGE_COLUMN, village);
contentValues.put(TALUKA_COLUMN, taluka);
contentValues.put(DISTRICT_COLUMN, district);
contentValues.put(TAGGING_DATE_COLUMN, tagging_date);
db.insert(TABLE_NAME_FARMER_SYNC, null, contentValues);
db.close();
return insurance_id;
}
then First Activity Code
private void addDataInTable() {
int insuranceId = databaseHelper.addFarmerName(id, bank_insured, bank_hypo, editTextFarmerName.getText().toString() + "", editTextVillage.getText().toString() + "", editTextTaluka.getText().toString() + "",
editTextDistrict.getText().toString() + "", editTextTaggingDate.getText().toString() + "");
if (insuranceId != 0) {
Intent i = new Intent(this, SecondActivity.class);
i.putExtra("id",insuranceId);
startActivityForResult(i, 1);
} else {
Toast.makeText(context, "Data Not Save in SQLite Database", Toast.LENGTH_SHORT).show();
}
}
in Second Activity
int id = getIntent().getStringExtra("id");
then
for(int count =0 ;count<animalList.size();count++){
boolean insertData = databaseHelper.addAnimalsName(tag_no, id, ear_position,
animal_species, animal_breed, body_color, shape_right, shape_left,
tail_switch, age, other_marks, prag_status, lactations, milk_qty,
sum_insured, NewEntryImg1, NewEntryImg2, NewEntryImg3, NewEntryImg4, NewEntryImg5,
NewEntryImg6);
}
if (insertData) {
Toast.makeText(context, "Data Save Successfully in SQLite Database",
Toast.LENGTH_SHORT).show();
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();
} else {
Toast.makeText(context, "Data Not Save in SQLite Database", Toast.LENGTH_SHORT).show();
}
Now in FirstActivity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
//success msg
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}//o

Only one column of data inserted in the sqlite database

So I'm using multiple radiogroup and an EditText to insert the data into the database. The problem is that only one column of data is inserted and it is always the the collection_time column.
This is the coding to insert the data:
BtnNext1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SelectPrintingDetails.this, Summary.class);
int selectedId = rgCP.getCheckedRadioButtonId();
if(selectedId != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId);
String rbCP = selectedRadioButton.getText().toString();
Boolean insertPD = db.insertcolor(rbCP);
if(insertPD == true)
{
intent.putExtra("Color", rbCP);
}
else
{
Toast.makeText(getApplicationContext(), "Data is not inserted",Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Radiobutton is not selected",Toast.LENGTH_SHORT).show();
}
int selectedId1 = rgFP.getCheckedRadioButtonId();
if(selectedId1 != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId1);
String rbFP = selectedRadioButton.getText().toString();
Boolean insertPD1 = db.insertflip(rbFP);
if(insertPD1 == true)
{
intent.putExtra("Flip", rbFP);
}
else
{
Toast.makeText(getApplicationContext(), "Data is not inserted",Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Radiobutton is not selected",Toast.LENGTH_SHORT).show();
}
int selectedId2 = rgPC.getCheckedRadioButtonId();
if(selectedId1 != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId2);
String rbPC = selectedRadioButton.getText().toString();
Boolean insertPD2 = db.insertpc(rbPC);
if(insertPD2 == true)
{
intent.putExtra("Plastic", rbPC);
}
else
{
Toast.makeText(getApplicationContext(), "Data is not inserted",Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Radiobutton is not selected",Toast.LENGTH_SHORT).show();
}
int selectedId3 = rgBind.getCheckedRadioButtonId();
if(selectedId1 != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId3);
String rbBind = selectedRadioButton.getText().toString();
Boolean insertPD3 = db.insertbind(rbBind);
if(insertPD3 == true)
{
intent.putExtra("Bind", rbBind);
}
else
{
Toast.makeText(getApplicationContext(), "Data is not inserted",Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Radiobutton is not selected",Toast.LENGTH_SHORT).show();
}
String timecollect = etCT.getText().toString();
Boolean insertPD4 = db.insertct(timecollect);
if(insertPD4 == true)
{
intent.putExtra("Collect", timecollect);
}
else
{
Toast.makeText(getApplicationContext(), "Data is not inserted",Toast.LENGTH_SHORT).show();
}
startActivity(intent);
}
});
This is the databasehelper :
public class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, "hdatabase1.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create table printingdetails (color text, binding text, collection_time text, flipped_page text, plastic_cover text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("drop table if exists printingdetails");
}
public boolean insertcolor(String color)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("color", color);
long ins = db.insert("printingdetails", null, contentValues);
if(ins==-1) return false;
else return true;
}
public boolean insertflip(String flipped_page)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("flipped_page", flipped_page);
long ins = db.insert("printingdetails", null, contentValues);
if(ins==-1) return false;
else return true;
}
public boolean insertpc(String plastic_cover)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("plastic_cover", plastic_cover);
long ins = db.insert("printingdetails", null, contentValues);
if(ins==-1) return false;
else return true;
}
public boolean insertbind(String binding)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("binding", binding);
long ins = db.insert("printingdetails", null, contentValues);
if(ins==-1) return false;
else return true;
}
public boolean insertct (String collection_time)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("collection_time", collection_time);
long ins = db.insert("printingdetails", null, contentValues);
if(ins==-1) return false;
else return true;
}
I hope you guys guide me how to insert all the data in every column. I'm still new and I had already refer to several related post here and none of it really helping
Currently you seem to be inserting the value of each column separately. This means instead of a single row, you end up with multiple rows where only one column has a value and the rest are empty.
In order to fix this, you need a single method which is something like this:
public boolean insertRow(String color, String binding, String time, String flipped_page, String plastic_cover) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("color", color);
contentValues.put("binding", binding);
contentValues.put("collection_time", time);
contentValues.put("flipped_page", flipped_page);
contentValues.put("plastic_cover", plastic_cover);
long ins = db.insert("printingdetails", null, contentValues);
if(ins==-1) return false;
else return true;
}
Each individual insert command should be removed. Now, your onClick method will have to retrieve all the selected items and then call this insert method. Handling of unselected radio groups will depend on your application. In the sample below, I am simply interrupting the method, thus cancelling the submission. If some radio groups are optional, then you can set the corresponding strings to empty ("") and proceed with the method rather than cancelling the submission by returning.
public void onClick(View v) {
Intent intent = new Intent(SelectPrintingDetails.this, Summary.class);
String color, binding, time, page, cover;
int selectedId = rgCP.getCheckedRadioButtonId();
if(selectedId != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId);
color = selectedRadioButton.getText().toString();
}
else
{
Toast.makeText(getApplicationContext(), "Color is not selected",Toast.LENGTH_SHORT).show();
return; // this prevents the rest of the code from executing
}
int selectedId1 = rgFP.getCheckedRadioButtonId();
if(selectedId1 != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId1);
page = selectedRadioButton.getText().toString();
}
else
{
Toast.makeText(getApplicationContext(), "FlipPage is not selected",Toast.LENGTH_SHORT).show();
return;
}
int selectedId2 = rgPC.getCheckedRadioButtonId();
if(selectedId2 != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId2);
cover = selectedRadioButton.getText().toString();
}
else
{
Toast.makeText(getApplicationContext(), "Plastic Cover is not selected",Toast.LENGTH_SHORT).show();
return;
}
int selectedId3 = rgBind.getCheckedRadioButtonId();
if(selectedId3 != -1)
{
RadioButton selectedRadioButton = (RadioButton) findViewById(selectedId3);
binding = selectedRadioButton.getText().toString();
}
else
{
Toast.makeText(getApplicationContext(), "Binding is not selected",Toast.LENGTH_SHORT).show();
return;
}
time = etCT.getText().toString();
// since all attributed have been read, now we call insert
// you can read the returned boolean to determine if the insertion was successful
db.insertRow(color, binding, time, page, cover);
// Also add all of them as intent extras
intent.putExtra("Color", color);
intent.putExtra("Bind", binding);
intent.putExtra("Collect", time);
intent.putExtra("Flip", page);
intent.putExtra("Plastic", cover);
startActivity(intent);
}
I hope this helps you understand where you were going wrong, and how you can take this forward.

Static Method error on fetching data in Android Studio through Sqlite

I'm new in this programming in Android Studio.I have a problem with this code that I write from a tutorial.
public void onClick(View v){
if (editusername.getText().toString().trim().length() == 0 || editpassword.getText().toString().trim().length() ==0) {
Toast.makeText(getApplicationContext(), "Semua Kolom harus Diisi", Toast.LENGTH_SHORT).show();}
else try{ String username = editusername.getText().toString().trim();
String password = editpassword.getText().toString().trim();
String query = "Select * From User where username = '"+username+"'";
if(DbManager.fetch().getCount()>0){
Toast.makeText(getApplicationContext(), "Already Exist!", Toast.LENGTH_SHORT).show();
}else{
DbManager.insert(username, password);
Toast.makeText(getApplicationContext(), "Added successfully!", Toast.LENGTH_SHORT).show();
}
}catch (Exception e) {
e.printStackTrace();
}
In the 'fetch' and 'insert' Method there was an error of 'cannot be referenced as static method'.
This is the code in the corresponding class DbManager
public void insert(String usn, String pwd) {
ContentValues contentValue = new ContentValues();
contentValue.put(SQLiteHelper.USERNAME, usn);
contentValue.put(SQLiteHelper.PASSWORD, pwd);
this.database.insert(SQLiteHelper.TABLE_NAME_USER, null, contentValue);
}
public Cursor fetch() {
Cursor cursor = this.database.query(SQLiteHelper.TABLE_NAME_USER, new String[]{SQLiteHelper._ID, SQLiteHelper.USERNAME, SQLiteHelper.PASSWORD}, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
You never created an instance of the DbManager class.
Adding an DbManager manager = new DbManager(); and then using manager.fetch() and manager.insert(params...) should solve your problem.
Doing Class.Method() is only possible if Method() was declares as public static void Method(). If it wasn't, you need to first create an object, then call the method on that object like I showed you above.

near "?": syntax error (code 1): , while compiling: UPDATE and DELETE

//deleting query
public void deleteFromQuestion(int questionId) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from Questions where question_id =" + questionId);
}
//updating query
public void updateQuestion(String question, String answerOne, String answerTwo, String answerThree, String answerFour, String correctAnswer, int id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("question", question);
contentValues.put("answer_one", answerOne);
contentValues.put("answer_two", answerTwo);
contentValues.put("answer_three", answerThree);
contentValues.put("answer_four", answerFour);
contentValues.put("correct_answer", correctAnswer);
db.update("Questions", contentValues,"question_id ?", new String[]{String.valueOf(id)});
}
and this is the code of update and delete
//update button code
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
questionStr = String.valueOf(questionET.getText());
answerOneStr = String.valueOf(ansOneET.getText());
answerTwoStr = String.valueOf(ansTwoET.getText());
answerThreeStr = String.valueOf(ansThreeET.getText());
answerFourStr = String.valueOf(ansFourET.getText());
correctAnswerStr = String.valueOf(correctAnsET.getText());
if (questionStr == null || answerOneStr == null || answerTwoStr == null || correctAnswerStr == null) {
Toast.makeText(getApplicationContext(), "Please Fill Fields ", Toast.LENGTH_SHORT).show();
} else {
questionManagerObject.updateQuestion(questionStr, answerOneStr, answerTwoStr, answerThreeStr, answerFourStr, correctAnswerStr, questionId);
Toast.makeText(getApplicationContext(), "Question Updated ", Toast.LENGTH_SHORT).show();
}
}
});
//delete button code
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
questionManagerObject.deleteFromQuestion(questionId);
Toast.makeText(getApplicationContext(), "Question deleted ", Toast.LENGTH_SHORT).show();
}
});
it is supposed to delete with the question id and update with it also these are buttons when click it , it will delete or update ...... this error, what's wrong with this code??
You missed adding "=" before "?".Change it to -
db.update("Questions", contentValues,"question_id = ?", new String[]{String.valueOf(id)});

Retrive my database values from my database and then using them on a programmatic SMS message?

I'm confused and cannot figure out how I can send an SMS message using values stored on my database.
The SMS would appear like this: ('NAME'... Message content, etc..), the message would then be sent using the contact numbers entered by the user on the sqlite database.
Here's the code I've used to get the data during signup.
public class LoginDataBaseAdapter {
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ "USERNAME text, PASSWORD text, NAME text, C1 integer, C2 integer); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context) {
context = _context;
dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException {
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void insertEntry(String userName,String password, String name, String cn1, String cn2) {
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("USERNAME", userName);
newValues.put("PASSWORD",password);
newValues.put("NAME",name);
newValues.put("C1", cn1);
newValues.put("C2", cn2);
// Insert the row into your table
db.insert("LOGIN", null, newValues);
// Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}
public int deleteEntry(String UserName) {
//String id=String.valueOf(ID);
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String getSingleEntry(String userName) {
Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if(cursor.getCount()<1) { // username doesn't exist
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public boolean isExist (String userName) {
boolean exists;
Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
if (cursor.getCount()>0) { // username exists
exists = true;
cursor.close();
return exists;
}
return false;
}
public void updateEntry(String userName,String password) {
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("USERNAME", userName);
updatedValues.put("PASSWORD", password);
String where="USERNAME = ?";
db.update("LOGIN",updatedValues, where, new String[]{userName});
}}
And here is the SignUpActivity
public class SignUpActivity extends AppCompatActivity {
Button bSignup;
TextView tvSign;
EditText etUN, etPW, etPW2, etFN, etC1, etC2;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
bSignup = (Button)findViewById(R.id.bSignup);
tvSign = (TextView)findViewById(R.id.tvSign);
etUN = (EditText)findViewById(R.id.etUN);
etPW = (EditText)findViewById(R.id.etPW);
etPW2 = (EditText)findViewById(R.id.etPW2);
etFN = (EditText)findViewById(R.id.etFN);
etC1 = (EditText)findViewById(R.id.etC1);
etC2 = (EditText)findViewById(R.id.etC2);
bSignup.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUN.getText().toString();
String password = etPW.getText().toString();
String password2 = etPW2.getText().toString();
String name = etFN.getText().toString();
String c1 = etC1.getText().toString();
String c2 = etC2.getText().toString();
// check if fields are vacant
if (username.equals("") || password.equals("") || password2.equals("") || name.equals("")
|| c1.equals("")|| c2.equals("")) {
Toast.makeText(getApplicationContext(), "Incomplete Data", Toast.LENGTH_SHORT).show();
return;
}
// check if passwords 1 and 2 match
if (!password.equals(password2)) {
Toast.makeText(getApplicationContext(), "Passwords don't match. Please try again.", Toast.LENGTH_LONG).show();
return;
}
//check is username is still available for use
if (loginDataBaseAdapter.isExist(username)){
Toast.makeText(getApplicationContext(),"Username already taken. Please try again.", Toast.LENGTH_LONG).show();
return;
}
else {
// allow data to be saved in the database
loginDataBaseAdapter.insertEntry(username, password, name, c1, c2);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
});
tvSign.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
}
}
Once I'm logged in, how can I get those values ("i.e. NAME, C1, and C2") and send an SMS by pushing a button?
Update
I've used this on my LoginDataBaseAdapter.
public HashMap<String, String> getUserDetails(){
HashMap <String,String> user = new HashMap <String,String> ();
String selectQuery = "SELECT * FROM " + "LOGIN";
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount()>0){
user.put("USERNAME", cursor.getString(1));
user.put("PASSWORD", cursor.getString(2));
user.put("NAME", cursor.getString(3));
user.put("C1", cursor.getString(4));
user.put("C2", cursor.getString(5));
}
cursor.close();
db.close();
// return user
return user;
}
Then this code at my HomeActivity:
tvHello = (TextView)findViewById(R.id.tvHello);
HashMap <String, String> details = loginDataBaseAdapter.getUserDetails();
String name_text = details.get("NAME");
tvHello.setText("Welcome " + name_text);
It seems that it can only get the first entry and not the current entry for the current user. Any ideas to fix this issue? Thank you very much.
Managed to get it right. So I'll answer my own question.
Create a editText area wherein you'll enter your name to retrieve. Then use this code to retrieve it
public String getData(String verif) {
Cursor cursor = db.query("LOGIN", null, " USERNAME=?", new String[]{verif}, null, null, null);
if(cursor.getCount()<1) {
cursor.close();
return "No records exist";
}
cursor.moveToFirst();
String get_name = cursor.getString(cursor.getColumnIndex("NAME"));
cursor.close();
return get_name;
}
Once retrieved, set the name in a TextView. Then convert it to string like so:
String myName = myTextView.getText().toString();
Then:
smsManager.sendTextMessage(number, null, "My name is "+ myName ,null,
null);
'number' is a String containing the contact number where you want to send your SMS

Categories

Resources