Android: How to Extract the data in 1 row with 2 columns - android

Here are my codes for my Search Activity
search.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
// Abstract Method of TextWatcher Interface.
}
public void beforeTextChanged(CharSequence s,
int start, int count, int after)
{
// Abstract Method of TextWatcher Interface.
}
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
textlength = search.getText().length();
array_sort.clear();
for (int i = 0; i < listview_array.length; i++)
{
if (textlength <= listview_array[i].length())
{
if(search.getText().toString().equalsIgnoreCase(
(String)
listview_array[i].subSequence(0,
textlength)))
{
array_sort.add(listview_array[i]);
}
}}
listContent1.setAdapter(new ArrayAdapter<String>
(Search_Food.this,
android.R.layout.simple_list_item_1, array_sort));
}
});
my onclicklistener code
AlertDialog.Builder adb = new AlertDialog.Builder(
Search_Food.this);
adb.setTitle("Food Item");
adb.setMessage("Selected Food is = "
+ listContent1.getItemAtPosition(position));
adb.setPositiveButton("Ok", null);
adb.show();
my Dbadapter
public LinkedList<String> search(String string) {
// TODO Auto-generated method stub
LinkedList<String> results = new LinkedList<String>();
Cursor cursor = null;
String search = string;
try{
cursor = this.sqLiteDatabase.query(true, MYDATABASE_TABLE , new String[] { KEY_ID , KEY_FOODNAME , KEY_CALORIES }, KEY_FOODNAME + " = ?" + "COLLATE NOCASE",
new String[] { search }, null, null, null, null);
if(cursor!=null && cursor.getCount()>0 && cursor.moveToFirst()){
int foodName = cursor.getColumnIndex(KEY_FOODNAME );
int keyColories = cursor.getColumnIndex(KEY_CALORIES );
// boolean moveToNext = cursor.moveToNext();
//do{
results.add(
new String(
cursor.getString(foodName) + " " +
cursor.getString(keyColories)
)
);
//}while(moveToNext);
}
}catch(Exception e){
Log.e(APP_NAME, "An error occurred while searching for "+search+": "+e.toString(), e);
}finally{
if(cursor!=null && !cursor.isClosed()){
cursor.close();
}
}
return results;
}
now when i click a data on my searched listview, i want to extract the getitemposition into 2 and thats my columns. the food name and the calories. how can i separate the 2 values.
answers please. help. thank you

Related

Filter a contact List through TextWatcher in Android

I'm showing contacts in a ListView and trying to filter the same list using an EditText. But when I type something, filtering is not happening, though the typed text is coming in Logcat.
Here is my onCreate:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_invite);
EditText filterText = findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
// The contacts from the contacts content provider is stored in this cursor
mMatrixCursor = new MatrixCursor(new String[]{"_id", "name", "details"});
// Adapter to set data in the listview
mAdapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.contact_layout, null, new String[]{"name", "details"}, new int[]{R.id.tv_name, R.id.tv_details}, 0);
// Getting reference to listview
ListView lstContacts = findViewById(R.id.lst_contacts);
// Setting the adapter to listview
lstContacts.setAdapter(mAdapter);
// Creating an AsyncTask object to retrieve and load listview with contacts
ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();
// Starting the AsyncTask process to retrieve and load listview with contacts
listViewContactsLoader.execute();
}
This is my TextWatcher:
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Log.d(TAG, "onTextChanged: " + s);
mAdapter.getFilter().filter(s.toString());
}
};
What am I doing wrong here? Can someone help?
EDIT: Adding my ListViewContactsLoader.
private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor> {
#Override
protected Cursor doInBackground(Void... params) {
Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;
// Querying the table ContactsContract.Contacts to retrieve all the contacts
Cursor contactsCursor = getContentResolver().query(contactsUri,
null, null, null,
ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
if (contactsCursor.moveToFirst()) {
do {
long contactId = contactsCursor.getLong(contactsCursor
.getColumnIndex("_ID"));
Uri dataUri = ContactsContract.Data.CONTENT_URI;
// Querying the table ContactsContract.Data to retrieve individual items like
// home phone, mobile phone etc corresponding to each contact
Cursor dataCursor = getContentResolver().query(dataUri,
null,
ContactsContract.Data.CONTACT_ID + "=" + contactId,
null, null);
String displayName = "";
String mobilePhone = "";
if (dataCursor.moveToFirst()) {
// Getting Display Name
displayName = dataCursor
.getString(dataCursor
.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
do {
// Getting Phone numbers
if (dataCursor
.getString(
dataCursor
.getColumnIndex("mimetype"))
.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)) {
switch (dataCursor.getInt(dataCursor
.getColumnIndex("data2"))) {
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
mobilePhone = dataCursor
.getString(dataCursor
.getColumnIndex("data1"));
break;
}
}
} while (dataCursor.moveToNext());
String details = "";
// Concatenating various information to single string
if (mobilePhone != null && !mobilePhone.equals(""))
details = mobilePhone + "\n";
// Adding id, display name, path to photo and other details to cursor
mMatrixCursor.addRow(new Object[]{
Long.toString(contactId), displayName, details});
}
} while (contactsCursor.moveToNext());
}
return mMatrixCursor;
}
#Override
protected void onPostExecute(Cursor result) {
// Setting the cursor containing contacts to listview
mAdapter.swapCursor(result);
Log.d(TAG, "onPostExecute: " + result);
}
}
You need to reset the ListViewadapter also after adding the text in EditText.
searchEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Text [" + s + "] - Start [" + start + "] - Before [" + before + "] - Count [" + count + "]");
if (count < before) {
listAdapter.resetData(); // MARK: Resetting adapter here
}
listAdapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
Note: resetData() is custom method in which you have to replace the List data with new List Data that appears after applying the Filter. Then finally notify the Adapter.

Android : TextView not show in TextWatcher listener

I want to show text in text view if condition is satisfied with equal method in Text-watcher.I have a string variable used in a method, and I would like to compare the EditText value to that variable and text view is update and if not then display the string with wrong code.But ui is not updated in TextWatcher.
Here is my code
private final TextWatcher vesselWatcher = new TextWatcher()
{
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
Log.e("beforeTextChanged ", " here !!! ");
}
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
public void afterTextChanged(Editable s)
{
if (s.length() == 0)
{
txtVesselName.setVisibility(View.GONE);
Log.e("afterTextChanged View ", " is gone !!!");
btnPost.setClickable(false);
btnPost.setEnabled(false);
Log.e("afterTextChanged ", " btnPost.setEnabled(false); !!!");
}
else
{
if(notations.contains(etxtVesselCode.getText().toString().trim()))
{
Log.e("AAA strNotations ", " Match !!! = " + etxtVesselCode.getText().toString().trim());
String notations = etxtVesselCode.getText().toString().trim();
SQLiteDatabase db = dbhelper.getWritableDatabase();
Cursor cursor = db.rawQuery("select * from VesselList where Notation " + "= ? ", new String[]{notations});
if (cursor.moveToFirst())
{
do
{
strVesselsTypeName = cursor.getString(cursor.getColumnIndex("VesselsTypeName"));
Log.e("strVesselsTypeName ", "= " + strVesselsTypeName );
SharedPreferences sp;
sp = getApplicationContext().getSharedPreferences(MyPREFERENCES, 0);
SharedPreferences.Editor e = sp.edit();
e.putString("xyz", etxtVesselCode.getText().toString().trim());
e.commit();
Log.e("Match","!!!!");
txtVesselName.setText(strVesselsTypeName);
btnPost.setClickable(true);
btnPost.setEnabled(true);
Log.e("afterTextChanged ", " btnPost.setEnabled(true); !!!");
} while (cursor.moveToNext());
} db.close();
}
else
{
Log.e("Not "," Match !!");
txtVesselName.setText("Wrong Code !!");
btnPost.setClickable(false);
btnPost.setEnabled(false);
}
}
}
};
Make txtVesselName TextView VISIBLE again after calling txtVesselName.txtVesselName when if condition is true:
txtVesselName. setVisibility(View.VISIBLE);

To get a field from sqlite database using its corresponding column field

I have created a database in sqlite for android with variables like Acc No, name, date etc etc.
i have many edit text in my activity. when the acc no is entered in Acc No edit text, the corresponding name should appear in below Name edit text. how to do that.
my DB code is given below
public void getName(Editable account_edit_txt){
"Acc_No " + account_edit_txt, null, null, null, null);
Cursor cursor = db.query(DATABASE_TABLE, new String[] {"Cust_Name","Acc_No"}, "Acc_No=?",new String[]{"account_edit_txt"}, null, null, null);
Log.e("running", "cursor run");
if(cursor!=null)
{
Log.e("running", "curosr is not null");
while(cursor.isFirst())
{
Log.e("running", "cursor while loop enter");
String temp = (cursor.getString(cursor.getColumnIndex("Cust_Name")));
String temp2 =(cursor.getString(cursor.getColumnIndex("Acc_No")));
Log.e("running", "id acc num" +temp+ " name"+temp2);
}
}
Activity code is given below
public class TransactionActivity extends Activity {
EditText acc_edit;
TextView acc_txt;
Editable account_edit_txt;
Connection connection;
String name;
SQLiteDatabase sdb;
AccountDBAdapter db = new AccountDBAdapter(this);
//
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.transaction_page);
acc_edit = (EditText) findViewById(R.id.edittext_Acc_No);
acc_txt = (TextView) findViewById(R.id.text_show_name);
final String editable = String.valueOf(acc_edit.getText());
Log.e("editable value", "" + account_edit_txt);
acc_edit.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int count,
int after) {
if (start >= 2) {
db.open();
account_edit_txt = acc_edit.getText();
db.getName(account_edit_txt);
db.close();
}
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
}
Below function will help you to retrieve account holder name for given account number.
Non need to fecth Acc_No again. Ad you are already have account number which user has inserted.
Also assuming that there will be only one record associated with the give account number.
public String getAccountHolderName(String accountNumber) {
String accountHolderName = null;
Cursor cursor = db.query(DATABASE_TABLE, new String[] { "Cust_Name" },
"Acc_No=?", new String[] { accountNumber }, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
accountHolderName = (cursor.getString(cursor
.getColumnIndex("Cust_Name")));
cursor.close();
}
return accountHolderName;
}

Pass row_id from one Activity to another so I can delete row from activity based on row_id

I am attempting to delete a record from my database,
Short Summary:
My database populates a listview
The user can click the listview and
view more details on a new activity
I want to able to delete the
record from this new activity
CODE
I have a class named ModuleDatabaseHandler that manages the database. In this, I have a method called getData() that populates records to a ListView in ActivityViewAll:
ModuleDatabaseHandler
public ArrayList<String> getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_MODULE_CODE,
KEY_MODULE_NAME, KEY_LECTURE_PRACTICAL,
KEY_LECTURE_PRACTICAL_SHORT, KEY_LECTURE_DAY,
KEY_LECTURE_DAY_SHORT, KEY_START_TIME, KEY_END_TIME,
KEY_LOCATION, ADDITIONAL_INFO };
Cursor c = ourDatabase.query(DATABASE_MODULES, columns, null, null,
null, null, null);
ArrayList<String> results = new ArrayList<String>();
int indexModCode = c.getColumnIndex(KEY_MODULE_CODE);
int indexLectPracShort = c.getColumnIndex(KEY_LECTURE_PRACTICAL_SHORT);
int indexLectDayShort = c.getColumnIndex(KEY_LECTURE_DAY_SHORT);
int indexLectStart = c.getColumnIndex(KEY_START_TIME);
int indexLectLoc = c.getColumnIndex(KEY_LOCATION);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
results.add(c.getString(indexModCode) + " "
+ c.getString(indexLectPracShort) + " "
+ c.getString(indexLectDayShort) + " "
+ c.getString(indexLectStart) + " "
+ c.getString(indexLectLoc));
}
return results;
}
This data is read in by ActivityViewAll:
ActivityViewAll
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_modules_test);
ModuleDatabaseHandler info = new ModuleDatabaseHandler(this);
info.open();
ArrayList<String> data = info.getData();
info.close();
l = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data);
l.setAdapter(adapter);
l.setOnItemClickListener(this);
}
I have another method in the ModuleDatabaseHandler class called getAllData() that allows the user to press a ListView item and read full details about the item on a new activity, ActivityFullDetails:
public String getAllData(int specified_position) {
// TODO Auto-generated method stub
int position = specified_position;
if(c.moveToPosition(specified_position)) {
String result = "";
for(int columnIndex = 0; columnIndex<c.getColumnCount();columnIndex++) {
result += c.getString(columnIndex)+" ";
}
return result;
} else {
throw new IllegalArgumentException("Row " + specified_position + " does not exist");
}
}
The data is transfered from the listView in ActivityViewAll to ActivityFullDetails using onItemClick:
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView temp = (TextView) view;
Toast.makeText(this, temp.getText() + " " + i, Toast.LENGTH_SHORT)
.show();
ModuleDatabaseHandler info = new ModuleDatabaseHandler(this);
info.open();
String module_info = info.getAllData(i);
info.close();
Intent fullModuleDetails = new Intent();
fullModuleDetails.setClassName("com.example.collegetimetable",
"com.example.collegetimetable.ModuleDetails");
fullModuleDetails.putExtra("list1", module_info);
startActivity(fullModuleDetails);
}
Back in the ModuleDatabaseHandler class, I created a method called deleteEntry to attempt to delete a row:
public void deleteEntry(long row){
ourDatabase.delete(DATABASE_MODULES, KEY_ROWID + "=" + row, null);
}
The Problem
How can I pass the ROW_ID from the ModuleDatabaseHandler class to the listView in ActivityViewAll and then to the ActivityFullDetails so I can delete the record?
SOLVED
Thanks to Serge who helped me solve this, by creating a getRowId method as seen in the accepted answer. Although I did have to add a cursor query within the method which is not shown in the accepted answer i.e.:
public int getRowID(int specified_position) {
String[] columns = new String[]{ KEY_ROWID, KEY_MODULE_CODE, KEY_MODULE_NAME, KEY_LECTURE_PRACTICAL, KEY_LECTURE_DAY, KEY_START_TIME,KEY_END_TIME, KEY_LOCATION, ADDITIONAL_INFO};
Cursor c = ourDatabase.query(DATABASE_MODULES, columns, null, null, null, null, null);
// rest of method as shown below
}
This method is called in the ActivityViewAll activity page from an instance of ModuleDatabaseHandler class, passed to the ActivityFullDetails page using putExtra,(and received using getIntent().getExtras as usual)..the delete method can then use the rowid.
Add function
public int getRowID(int specified_position) {
int position = specified_position;
if(c.moveToPosition(specified_position)) {
return c.getInteger(c.getColumnIndex(KEY_ROWID));
} else {
throw new IllegalArgumentException("Row " + specified_position + " does not exist");
}
}
And then to get it use
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView temp = (TextView) view;
Toast.makeText(this, temp.getText() + " " + i, Toast.LENGTH_SHORT)
.show();
ModuleDatabaseHandler info = new ModuleDatabaseHandler(this);
info.open();
String module_info = info.getAllData(i);
int rowID = info.getRowID(i);
info.close();
Intent fullModuleDetails = new Intent();
fullModuleDetails.setClassName("com.example.collegetimetable",
"com.example.collegetimetable.ModuleDetails");
fullModuleDetails.putExtra("list1", module_info);
fullModuleDetails.putExtra("rowid", rowID);
startActivity(fullModuleDetails);
}

How to implement TextWatcher for SearchDialog

I need to update my ListView according to the userinput in SearchDialog. For this I need to set a TextWatcher for SearchDialog. How to do this?
you can do it as below:
yourEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// process new items for list view
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// push new items into adapter and call notifyDataSetChanged() on it
}
});
Here is what I did actually a few months ago to achieve the same thing that you need. I had to sort my list view depending on user input while I was populating the list view from sqlite database with sqlite statements. Not sure if it's the best way,but in my situation it works perfectly.
So on my EditText field I add this (which name is searchBar) :
searchString = "";
searchBar.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
// this is where actually I was changing the sqlite statement which sort my list view
names.clear();
categories.clear();
paths.clear();
count.clear();
cardId.clear();
myCardID.clear();
searchString = s.toString();
Log.e("","searchString : "+searchString);
sqlQuery = getSqlStatement(sort, collId, ascDesc,searchString);
Log.e(""," sqlquery : "+sqlQuery);
sqlQuery = getSqlStatement(sort, collId, ascDesc, searchString);
Cursor cursor = userDbHelper.executeSQLQuery(sqlQuery);
if (cursor.getCount() == 0) {
noCards.setVisibility(View.VISIBLE);
} else if (cursor.getCount() > 0) {
noCards.setVisibility(View.GONE);
for (cursor.move(0); cursor.moveToNext(); cursor.isAfterLast()) {
objectId = Integer.parseInt(cursor.getString(cursor.getColumnIndex("objectId")));
cardId.add(objectId);
title = cursor.getString(cursor.getColumnIndex("title"));
catTitle = cursor.getString(cursor.getColumnIndex("catTitle"));
if(extra!=0 && sort!=3){
tags.setText(catTitle);
}
int repeats = Integer.parseInt(cursor.getString(cursor.getColumnIndex("repeatsCount")));
count.add(repeats);
String cardsm = "SELECT objectId FROM cardmedias " +
"WHERE cardId="+
objectId +
" AND mediaType=" +
5012;
Cursor cardsM = userDbHelper.executeSQLQuery(cardsm);
if (cardsM.getCount() == 0) {
String defCard = "SELECT objectId FROM collectionmedias " +
"WHERE collectionId="+
collId +
" AND mediaType=" +
3003;
Cursor getDefCard = userDbHelper.executeSQLQuery(defCard);
getDefCard.moveToFirst();
objectID = Integer.parseInt(getDefCard.getString(getDefCard
.getColumnIndex("objectId")));
String filename = "mediacollection-"+objectID;
if(storageID==1){
path = RPCCommunicator.getImagePathFromInternalStorage(servername, userId, filename, getApplicationContext());
} else if(storageID==2){
path = RPCCommunicator.getImagePathFromExternalStorage(servername, userId, filename);
}
hm.put(objectID, path);
path = hm.get(objectID);
paths.add(path);
names.add(title);
categories.add(catTitle);
} else if (cardsM.getCount() > 0) {
for (cardsM.move(0); cardsM.moveToNext(); cardsM.isAfterLast()) {
objectID = Integer.parseInt(cardsM.getString(cardsM
.getColumnIndex("objectId")));
String filename = "mediacard-"+objectID;
if(storageID==1){
path = RPCCommunicator.getImagePathFromInternalStorage(servername, userId, filename, getApplicationContext());
} else if(storageID==2){
path = RPCCommunicator.getImagePathFromExternalStorage(servername, userId, filename);
}
hm.put(objectID, path);
path = hm.get(objectID);
paths.add(path);
names.add(title);
categories.add(catTitle);
}
}
cardsM.close();
}
}
cursor.close();
// don't forget to add this!!!
adapter.notifyDataSetChanged();
}
});
And in my onCreate() actually I'm doing the same thing as in TextWatcher to sort my list view, so I think you can implement the same logic as I did.
If you have any problems to do that, just paste some of your code so we can help you! : )
Hope this helps!

Categories

Resources