Run query in android SQLite database - android

I've a database in android studio that has a table name EMP_TABLE with columns E_NAME, E_AGE and E_DEPT.
My fragment layout has two editText fields, a button and a TextView field. I want to perform a query on that database such that when I enter the E_NAME attribute in 1st edittext field, E_AGE attribute in 2nd edittext field and press the button the corresponding attribute of E_AGE field appear in textView field.
The query looks like SELECT E_AGE FROM EMP_TABLE WHERE E_NAME=a1 AND E_DEPT=a2. I'm not so familier with the cursor and the query, help me with this.
This is what I did so far in my OnClick method. Any help will be appreciated.
actTextView1 = (AutoCompleteTextView) view.findViewById(R.id.acTextView1);
actTextView2 = (AutoCompleteTextView) view.findViewById(R.id.acTextView2);
result = (TextView) view.findViewById(R.id.resultField);
calculateButton = (Button) view.findViewById(R.id.calBtn);
calculateButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
DatabaseHelper myDBhelper = new DatabaseHelper(getActivity());
String a1 = actTextView1.getText().toString();
String a2 = actTextView2.getText().toString();
c = myDBhelper.query("EMP_TABLE", null, null, null, null, null, null);
if (c.moveToFirst()) {
do {
Toast.makeText(getActivity(), "Age is: " + c.getString(0), Toast.LENGTH_LONG).show();
} while (c.moveToNext());
}

To insert:
public void insertIntoTable(String E_NAME_VALUE, String E_AGE_VALUE,String E_DEPT_VALUE) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(E_NAME, E_NAME_VALUE);
cv.put(E_AGE, E_AGE_VALUE);
cv.put(E_DEPT, E_DEPT_VALUE);
db.insert(EMP_TABLE , null, cv);
}
To Fetch stored value from database:
public String fetchValueFromTable(String E_NAME_VALUE,String E_DEPT_VALUE) {
String E_AGE_VALUE="" ;
SQLiteDatabase db = this.getWritableDatabase();
SELECT E_AGE FROM EMP_TABLE WHERE E_NAME=a1 AND E_DEPT=a2
String query = "SELECT * FROM " + EMP_TABLE + " WHERE " + E_NAME+ "='" + E_NAME_VALUE+ "' ANd "+ E_DEPT+ "='" + E_DEPT_VALUE;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
E_AGE_VALUE=cursor.getString(cursor.getColumnIndex(E_AGE));
}
return E_AGE_VALUE;
}

Related

Delete specific row in SQLite Database

So, in my app you have to add eletrical equipment to every room in the house so it can measure how much energy you spend and etc.
What I want is when I click the button to remove a specific equipment, that equipment will be deleted from the database where it was stored, and this would be with only the name of the equipment as entry.
I have a code but when I hit the remove button the app kinda crashes and goes back to the home activity.
Can someone help pls?
That's the button:
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
button2.setVisibility(View.GONE);
tableLayout1.setVisibility(View.GONE);
imageView1.setVisibility(View.GONE);
textView12.setVisibility(View.GONE);
DatabaseOperations DOP;
String equipamento;
equipamento = textView12.getText().toString();
DOP = new DatabaseOperations(CTX);
Cursor CR = DOP.getUserInfo(DOP, equipamento);
CR.moveToFirst();
DOP.deleteEquip(DOP, equipamento);
Toast.makeText(getBaseContext(),"O equipamento foi removido com sucesso.", Toast.LENGTH_LONG).show();
}
});
And this is the class:
public Cursor getUserInfo (DatabaseOperations DOP, String equipamento){
SQLiteDatabase SQ = DOP.getReadableDatabase();
String selection = TableData.TableInfo.EQUIPAMENTO +" LIKE ?";
String coloumns[] = {TableData.TableInfo.POTENCIA, TableData.TableInfo.QUANT, TableData.TableInfo.HORAS, TableData.TableInfo.SIMULT};
String args [] = {equipamento};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, coloumns, selection, args, null, null, null);
return CR;
}
public void deleteEquip(DatabaseOperations DOP, String equipamento){
String selection = TableData.TableInfo.EQUIPAMENTO;
String args[] = {equipamento};
SQLiteDatabase SQ = DOP.getWritableDatabase();
SQ.delete(TableData.TableInfo.TABLE_NAME, selection, args);
}
#EngWatt this code is in the DBHelper Class you will need to change the rowid to reflect the name of the item you want to delete. I assume that is equipamento
We hope you have a MVP design to make all this easy
/* Delete a record from database table named "TABLE_INFO" */
/* based on the selected records id in Col_ID*/
public void deleteDBRow(String rowid){
db = this.getWritableDatabase();
db.delete(TABLE_INFO, Col_ID + " = ?", new String[] { rowid });
db.close();
return;
}

Retrieving specific data based on ID from SQLite in ANDROID

I wrote a code in which i can retrieve the data from the database but when i run it and try to search something. The application crashes as soon as i press Submit
public class search extends AppCompatActivity {
Button SearchButton;
EditText SearchText;
TextView SearchResult;
SQLiteDatabase db;
String builder;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
SearchButton=(Button)findViewById(R.id.searchbutton);
SearchText=(EditText)findViewById(R.id.Searchtext);
SearchResult=(TextView)findViewById(R.id.SearchCourse);
db=this.openOrCreateDatabase("Courses", Context.MODE_PRIVATE,null);
SearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int GetID = Integer.valueOf(SearchText.getText().toString());
Cursor TuplePointer = db.rawQuery("Select from Course where ID="+GetID+"",null);
TuplePointer.moveToFirst();
String Course = TuplePointer.getString(TuplePointer.getColumnIndex("Course"));
SearchResult.setText(Course);
}
});
}
}
Replace this line
Cursor TuplePointer = db.rawQuery("Select from Course where ID=" + GetID + "", null);
with
Cursor TuplePointer = db.rawQuery("Select Course from Course where ID=" + GetID + "", null);
Where Course is your column name
Write your code within try catch first. Afterthat try to catch exact exception. you will be clear what are you doing wrong.
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS + " Where " + KEY_APP_BOOKINGID + " = " + id;
Cursor cursor = db.rawQuery(selectQuery, null);
Please Try this
SQLiteDatabase db = this.getReadableDatabase();
String GetID = SearchText.getText().toString();
Cursor cursor = db.rawQuery("SELECT * FROM Course WHERE ID = ?", new String[]{String.valueOf(GetID)}, null);
if (cursor.moveToFirst()) {
do {
String Course = cursor.getString(cursor.getColumnIndex("Course"));
SearchResult.setText(Course);
} while (cursor.moveToNext());
}
Thank You everyone I figured out what i was doing wrong on the get Column index i targeted course but what i didnt realize is that there was no such field as course :)
Keep practice like below code you will debug proper
public void getFirstName(String id) {
String sql = "select first_name from basic_info WHERE contact_id="+ id;
Cursor c = fetchData(sql);
if (c != null) {
while (c.moveToNext()) {
String FirstName = c.getString(c.getColumnIndex("first_name"));
Log.e("Result =>",FirstName);
}
c.close();
}
return data;
}
public Cursor fetchData(String sql) {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery(sql, null);
}

How to put and get the current date by using simple database

I'm a beginner and don't know how to insert and get the current date by using database.
For an insert into the database, I use a button for adding the information. Here is the full code:
public void Badd_Click(View view) {
db.execSQL("INSERT INTO Demo (event, venue, amount, textView) VALUES ('" + tEvent.getText().toString() + "'," + "'" + tLocation.getText().toString() + "'," + "'" + tAmount.getText().toString() +"' )");
Toast.makeText(this, "Create record successfully...", Toast.LENGTH_SHORT).show();
}
Then, for showing the information inserted into the database, I also use a button:
public void Btnshow_Click(View view){
String str = "";
Cursor c = db.rawQuery("SELECT * FROM "+DATABASE_TABLE,null);
c.moveToFirst();
for(int i = 0; i<c.getCount();i++){
str+="ID: "+c.getString(0)+"\n";
str+="Name : "+c.getString(1)+"\n";
str+="Location : "+c.getString(2)+"\n";
str+="Amount : "+c.getString(3)+"\n\n";
c.moveToNext();
}
I have searched for many solutions, but I am unable to do it successfully.
Please help :(
You can use below two methods to save and retrieve date from database in the format you want.
public static String getDbDateString(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
return sdf.format(date);
}
public static Date getDateFromDb(String dateText) {
SimpleDateFormat dbDateFormat = new SimpleDateFormat("yyyyMMdd");
try {
return dbDateFormat.parse(dateText);
} catch ( ParseException e ) {
e.printStackTrace();
return null;
}
}
You can get current date with below code:
Date date = new Date(System.currentTimeMillis());
To add to database:
public void addDate() {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("key", "value");
// Inserting Row
db.insert(table_name, null, values);
db.close(); // Closing database connection
}
To read from database:
public Date getDate(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(table_name,
new String[]{column_id,
column_date_value},
column_id + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
assert cursor != null;
return new Date(cursor.getString(index_column_date));
}

SQLite database update query with multiple where conditions in Android

I want to update my database table with multiple where conditions. I already did with single where condition
db.update(TABLE_MISSING_ITEMS, values, KEY_AUTHOR + " = ?",
new String[] { String.valueOf(items.getAuthor()) });
Now i want 2 where condition.
P.S :- No raw query
You can separate the different WHERE conditions with ANDlike this:
db.update(TABLE_NAME,
contentValues,
NAME + " = ? AND " + LASTNAME + " = ?",
new String[]{"Manas", "Bajaj"});
The way I solved my need
public boolean checkHususiKayit(String baslik, String tarih) {
boolean varMi = false;
SQLiteDatabase database = dbHelper.getReadableDatabase();
final String kolonlar[] = {DBHelper.COLUMN_H_ID,
DBHelper.COLUMN_H_ID,
DBHelper.COLUMN_H_BASLIK,
DBHelper.COLUMN_H_TARIH,
DBHelper.COLUMN_H_YOK_TUR,
DBHelper.COLUMN_H_AD,
DBHelper.COLUMN_H_WEB_ID,
DBHelper.COLUMN_H_NUMARA,
DBHelper.COLUMN_H_YURD_ID,
DBHelper.COLUMN_H_YETKILI_AD,
DBHelper.COLUMN_H_YETKILI_ID,
DBHelper.COLUMN_H_TEL,
DBHelper.COLUMN_H_EMAIL,
DBHelper.COLUMN_H_ADDRESS,
DBHelper.COLUMN_H_VAR,
DBHelper.COLUMN_H_GOREVLI,
DBHelper.COLUMN_H_YOK,
DBHelper.COLUMN_H_IZINLI,
DBHelper.COLUMN_H_HATIMDE};
String whereClause = DBHelper.COLUMN_H_BASLIK + " = ? AND " + DBHelper.COLUMN_H_TARIH + " = ?"; // HERE ARE OUR CONDITONS STARTS
String[] whereArgs = {baslik, tarih};
Cursor cursor = database.query(DBHelper.TABLE_NAME_HUSUSI, kolonlar, whereClause, whereArgs, null, null, null + " ASC");
while (cursor.moveToNext()) {
varMi = true;
}
database.close();
cursor.close();
return varMi;
}
THIS CAN ALSO BE DONE LIKE THIS
public void UpdateData(int Cid,int flag,String username,String password)
{
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("Status",flag);//I am updating flag here
database.update(TABLE_NAME, cv, ""+KEY_UserName+"= '"+ username+"' AND "+KEY_CID+"='"+Cid+"' AND "+KEY_Password+"='"+password+"'" , null);
database.close();
}
Try this simple query
db.update(TABLE_FF_CHECKLIST_DATA,contentValues, "FFCHECKLISTID = ? and TASK_ID_CHK = ?" , new String[] {"EHS" , "CTO914"});
where "EHS" is value in column FFCHECKLISTID and CTO914 is value in TASK_ID_CHK.

Android: Get entire column data

Im trying to get the data of an entire column into a string array. My database contains two columns Id and Names. I want to read all the entries of the names column and put it into a array. Please help.
EDIT #1:
Im using the following code but i can get only one name with this code.
String query = "Select * FROM " + TABLE_APPS + " WHERE " + COLUMN_NAME + " = \"" + productname + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
cursor.moveToFirst();
name = cursor.getString(1);
cursor.close();
} else {
name = null;
}
db.close();
int total=0;
Cursor csr=sdb.query("tablename", null, null,null,null,null,null);
csr.moveToFirst();
while(!csr.isAfterLast())
{
total++;
csr.moveToNext();
}
String strarray[] = new String[total];
Cursor csrs=sdb.query("tablename", null, null,null,null,null,null);
csrs.moveToFirst();
int aray=0;
while(!csrs.isAfterLast())
{
strarray[aray]=csrs.getString(1);
aray++;
csrs.moveToNext();
}

Categories

Resources