i want to search in database in my android application. when i get a select query if its been or not been in database its show nothing.
this is my code:
final String havy = edtSearch.getText().toString();
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Cursor cursor = G.dataBase.rawQuery("SELECT * FROM db WHERE info_title=" + "'" + havy + "'", null);
if (cursor.moveToNext()) {
Intent intent = new Intent(SearchActivity.this, DetailActivity.class);
intent.putExtra(G.selectedItem.face, true);
SearchActivity.this.finish();
} else {
Toast.makeText(SearchActivity.this, "shows something", Toast.LENGTH_SHORT).show();
}
}
});
Check if your cursor is not null and size is greater that zero, then iterate over the cursor.
Related
By using assets folder, we are reading data i.e,address details based on search keyword:
Here is my code
private SQLiteDatabase db;
private Cursor c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_search = (EditText) findViewById(R.id.et_search);
img = (ImageView) findViewById(R.id.img_search);
list = (ListView) findViewById(R.id.list_search);
db = openOrCreateDatabase("sample", Context.MODE_PRIVATE, null);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
search_keyword = et_search.getText().toString();
arr_data = new ArrayList<ListItems>();
if (isValid()) {
SELECT_SQL = "SELECT ROWID AS _id,* FROM Addresses where Type LIKE '%" + search_keyword + "%'";
Log.d("daatt",SELECT_SQL);
try {
c = db.rawQuery(SELECT_SQL, null);
c.moveToFirst();
showRecords();
} catch (SQLiteException e) {
Toast.makeText(getApplicationContext(), "No Data", Toast.LENGTH_LONG).show();
}
}
}
});
}
private void showRecords() {
String ugName = c.getString(c.getColumnIndex("Name"));
String ugaddress = c.getString(c.getColumnIndex("Address"));
String ugtype = c.getString(c.getColumnIndex("Type"));
ListItems items = new ListItems();
// Finish reading one raw, now we have to pass them to the POJO
items.setName(ugName);
items.setAddress(ugaddress);
items.setType(ugtype);
// Lets pass that POJO to our ArrayList which contains undergraduates as type
arr_data.add(items);
}
ListDataAdapter adapter = new ListDataAdapter(arr_data);
list.setAdapter(adapter);
if (c != null && !c.isClosed()) {
int count = c.getCount();
c.close();
}
Log.d("ListData", "" + arr_data);
}
private boolean isValid() {
if (search_keyword.length() == 0) {
Toast.makeText(getApplicationContext(), "please enter valid key word", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
For 1st build we got successful data loaded using list adapter
But after clean project, & Rebuild project showing a no such table expection
Please guide us wr we r going wrong
Advance Thanks
As far as I can see from your print, the table you're referring to is called ListOfAddress, ain't it? your SQL is:
SELECT_SQL = "SELECT ROWID AS _id,* FROM Addresses where Type LIKE '%" + search_keyword + "%'";
I might be wrong, but I would double check the query.
I'm working on an SQLite Android app. I want to get rid of any duplicates while inserting data to the table.
My code:
Method from DatabaseHelper class (RCOL_2 is String):
public Cursor getResourceName(String condition) {
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("SELECT " + RCOL_2 + " FROM " + RESOURCE_TABLE + " WHERE " + RCOL_2 + " = " + "'" + condition + "'", null);
return cursor;
}
MainActivity:
public boolean checkResourceDuplicates(String insert) {
Cursor result = databaseHelper.getResourceName(insert);
StringBuffer buffer = new StringBuffer();
ArrayList<StringBuffer> values = new ArrayList<>();
while (result.moveToNext()) {
buffer.append(result.getString(0));
}
values.add(buffer);
for (int i=0; i < values.size(); i++) {
if(values.get(i).toString().equals(insert)){
return true;
}
}return false;
}
public void addResource() {
btnAddResource.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
if(checkResourceDuplicates(editResourceName.getText().toString())) {
Toast.makeText(MainActivity.this, "Duplicate", Toast.LENGTH_LONG).show();
}else{
boolean isInserted = databaseHelper.insertResource(editResourceName.getText().toString(), addCategoryID(spinner.getSelectedItem().toString()));
if (isInserted == true) {
editResourceName.setText(null);
Toast.makeText(MainActivity.this, "Resource added", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Resource not added", Toast.LENGTH_LONG).show();
}
}
}
}
);
}
For now, it allows to add to the database for example: 'a' and 'A'.
I tried with equalsIgnoreCase method, selecting lower from the database... and nothing. In the best case I managed to prevent adding 'AaAa' after adding 'aaaa', but adding 'aaaa' after 'AaAa' was allowed.
I tried SELECT LOWER(column_name), adding it to array list, converting insert value to lowerCase and matching these. Didn't work. I don't want to make additional trash table in my database to validate this.
if i follow your question.. you need to convert your text to lowercase then insert it into a separate column >> apply unique attribute on it.. and insert with insertWithOnConflict.. something like that.
while creating table..
KEY_NAME+" TEXT UNIQUE"
and insert data as.
db.insertWithOnConflict(TABLE_NAME, null, values, SQLiteDatabase.CONFLICT_IGNORE);
//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)});
UI for this
User interface
and database
Sqlite Database
In my Code I want to compare selected Radio button is equal to the account type in database.
If they equal it must start activity as stated in the if statement.
I hardcoded my account type and it works but now i want to grab the account type from database and compare it with the string of selected radio button
//Button To submit selected Radio button for a specicific account
public void onClickSubmitAccount(){
radio_accounts = (RadioGroup) findViewById(R.id.radioAccounts);
btnSubmitAccount = (Button) findViewById(R.id.btnSubmitAccount);
btnSubmitAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int selected_account = radio_accounts.getCheckedRadioButtonId();
radio_button_accounts = (RadioButton) findViewById(selected_account);
Toast.makeText(UserHomePageActivity.this, radio_button_accounts.getText().toString(), Toast.LENGTH_SHORT).show();
if ((radio_button_accounts.getText().toString()).equals("Savings Account")) {
Intent accountIntent = new Intent(UserHomePageActivity.this, SavingsTransactionsActivity.class);
startActivity(accountIntent);
}
else if ((radio_button_accounts.getText().toString()).equals("Credit Account")) {
Intent accountIntent = new Intent(UserHomePageActivity.this, CreditTransactionActivity.class);
startActivity(accountIntent);
}
else if ((radio_button_accounts.getText().toString()).equals("Cheque Account")) {
Intent accountIntent = new Intent(UserHomePageActivity.this, ChequeTransactionActivity.class);
startActivity(accountIntent);
}
else {
Toast.makeText(UserHomePageActivity.this, "Sorry, No accout has been selected", Toast.LENGTH_LONG).show();
}
}
});
}
//Retrieve Data from DataBase in Table Account
public ArrayList getAllAccount()
{
ArrayList<AccountClass> accountList = new ArrayList<AccountClass>();
Cursor cursor = bankingAppDB.query(Constants.tblAccount, null,null,null,null,null,null);
AccountClass account;
if(cursor.moveToFirst()){
while (cursor.moveToNext())
{
String acc_number = cursor.getString(cursor.getColumnIndex(Constants.ACCOUNT_NUMBER));
String account_type = cursor.getString(cursor.getColumnIndex(Constants.ACCOUNT_TYPE));
double balance = Double.parseDouble(cursor.getString(cursor.getColumnIndex(Constants.ACCOUNT_BALANCE)));
Log.d(" Info"," Account Number: " +acc_number+" type: "+account_type);
account = new AccountClass(acc_number);
accountList.add(account);
}
}
return accountList;
}
//Adding Account number, Account Type and Balance to Account Table
public void addAccount(AccountClass account){
ContentValues values = new ContentValues();
values.put(Constants.ACCOUNT_NUMBER, account.getAccountNumber());
values.put(Constants.ACCOUNT_BALANCE, account.getAccountBalance());
values.put(Constants.ACCOUNT_TYPE, account.getAccountType());
bankingAppDB.insert(Constants.tblAccount, null, values);
bankingAppDB.close();
}
First of all your AccountClass is only receiving the account number attribute, there for you are not storing the rest of the values in your object.
Change your constructor to get all the 3 attributes
account = new AccountClass(acc_number, account_type, balance);
Secondly, you should have a method that gets an Account by it's number
public List<AccountClass> getAccountsByNumber(String number){
ArrayList<AccountClass> accountList = new ArrayList<AccountClass>();
String query = "SELECT * FROM " + YOUR_TABLE + " WHERE " + ACCOUNT_NUMBER + " = " + number;
Cursor cursor = bankingAppDB.query(query, null,null,null,null,null,null);
if(cursor.moveToFirst()){
while (cursor.moveToNext())
{
String acc_number = cursor.getString(cursor.getColumnIndex(Constants.ACCOUNT_NUMBER));
String account_type = cursor.getString(cursor.getColumnIndex(Constants.ACCOUNT_TYPE));
double balance = Double.parseDouble(cursor.getString(cursor.getColumnIndex(Constants.ACCOUNT_BALANCE)));
Log.d(" Info"," Account Number: " +acc_number+" type: "+account_type);
AcountClass account = new AccountClass(number,account_type,balance);
accountList.add(account);
}
}
return accountList;
}
After that, assuming you know your user id, on your onClick method call
List<AccountClass> accountList = bankingAppDB.getAccountsByNumber(NUMBER_OF_THE_ACCOUNT);
and then
for(AccountClass a : accountList){
if ((radio_button_accounts.getText().toString()).equals(a.getAccountType()) && a.getAccountType().trim().equals("Savings Account")) {
Intent accountIntent = new Intent(UserHomePageActivity.this, SavingsTransactionsActivity.class);
startActivity(accountIntent);
}
else if ((radio_button_accounts.getText().toString()).equals(a.getAccountType())&& a.getAccountType().trim().equals("Credit Account")) {
Intent accountIntent = new Intent(UserHomePageActivity.this, CreditTransactionActivity.class);
startActivity(accountIntent);
}
else if ((radio_button_accounts.getText().toString()).equals(a.getAccountType())&& a.getAccountType().trim().equals("Cheque Account")) {
Intent accountIntent = new Intent(UserHomePageActivity.this, ChequeTransactionActivity.class);
startActivity(accountIntent);
}
else {
Toast.makeText(UserHomePageActivity.this, "Sorry, No accout has been selected", Toast.LENGTH_LONG).show();
}
}
My Activity Code
Please help me how to delete item in list view that connect to database in Android Studio. This my code :
mainListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView parent, View view, final int position, final long id) {
final AlertDialog.Builder b = new AlertDialog.Builder(UserList.this);
b.setIcon(android.R.drawable.ic_dialog_alert);
b.setMessage("Ingin menghapus data?");
b.setPositiveButton("Ya",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
IDTable = IDList.get(position);
userList.remove(position);
UserList.this.listAdapter.notifyDataSetChanged();
InfoPokok info = new InfoPokok();
info.setId(IDTable);
System.out.println("ID : " + info.getId());
infoPokokDao.deleteInfoPokok(info);
}
});
b.setNegativeButton("Tidak",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
b.show();
return true;
}
});
DAO :
public void deleteInfoPokok(InfoPokok infoPokok) {
String id = infoPokok.getId() + "";
long deleteId = database.delete(MySQLiteHelper.TABLE_INFO_POKOK, MySQLiteHelper.COLUMN_ID
+ " =?", new String[]{id});
Cursor cursor = database.query(MySQLiteHelper.TABLE_INFO_POKOK,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + deleteId, null,
null, null, null);
cursor.moveToFirst();
cursor.close();
}
IN YOUR DISPLAYACTIVITY.JAVA
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHandler db = new DataBaseHandler(DisplayImageActivity.this);
Log.d("Delete Image: ", "Deleting.....");
db.deleteCloth(new Cloth(imageId));
Intent i = new Intent(DisplayImageActivity.this, MainActivity.class);
startActivity(i);
finish();
}
});
AND THEN IN DATABASEHANDLER.JAVA
public void deleteCloth(Cloth cloth) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CLOTHES, KEY_ID + " = ?", new String[] { String.valueOf(cloth.getID()) });
db.close();
}
I think the best way to achieve this is to write a delete method in your Provider :
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
//the provided is requested to delete data - so we'll delete it in the db:
SQLiteDatabase db = dbHelper.getWritableDatabase();
int result = db.delete(getTableName(uri), selection, selectionArgs);
// notify the change
getContext().getContentResolver().notifyChange(uri, null);
//return the number of rows deleted
//it's what we got from the db.delete
return result;
}
and then just call it like :
getContentResolver().delete(YOUR_CONTENT_URI, String where, String[] selectionArgs);
Do u use CursorAdapter or ArrayAdapter?
CursorAdapter - 1. Use AsyncTask or something that u build that delete the data on back thread and not on the UI (currently onLongClick is being called on the UI and you are accessing DB on the UI, bad practice). 2. When the delete is done you can restart your loader to requery the DB and the cursor wil update. Think about maybe showing a progress bar if u will have a large DB or adding calls to server.
ArrayAdapter - Based on array adpter that is a place holder for the cursor. 1. Delete the data from the array and notifyDataSetCahnged, UI thread.
2. Delete the item from DB on back thread.
This way the user wont feel any Glitch.
Good luck.