I have written a program to get some values from sqlite database and populate inside spinner ,which is working perfectly , but i want to show the selected item from the spinner into a different activity , all i am getting is either a blank value or android.database.sqlite.SQLiteCursor#3456046c , so how to convert it to string ??
Need some help
int[] to = new int[] { android.R.id.text1 };
String[] from = new String[] { DbListHelper.ACCOUNT_TYPE };
final SimpleCursorAdapter adapter4 = new SimpleCursorAdapter(
getBaseContext(), android.R.layout.simple_list_item_1, cursor,
from, to) {
public View getView(int position, View convertView, ViewGroup
parent) {
View v = super.getView(position, convertView, parent);
((TextView) v).setTextSize(18);
((TextView) v).setGravity(Gravity.CENTER);
((TextView) v).setTextColor(Color.parseColor("#1C689C"));
return v;
}
};
adapter4.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinnerType.setAdapter(adapter4);
On button click to save the records i am doing this , acName is the spinner variable which i am inserting , i also tried to put a dummy value inside acName as acName = "1" , which is showing properly .
btnPrint.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(cursor.moveToFirst()){
do {
acName =
cursor.getString(cursor.getColumnIndex(DbListHelper.ACCOUNT_NAME));
} while (cursor.moveToNext());
}
vehicleNo1 = editVehicleNo1.getText().toString();
driverName = editDriverName.getText().toString();
driverCode = editDriverCode.getText().toString();
dieselRate = editDieselRate.getText().toString();
dieselQty = editDieselQty.getText().toString();
amount = editAmount.getText().toString();
referenceNo = editReferenceNo.getText().toString();
noOfCopies = editNoOfCopies.getText().toString();
remark = editRemark.getText().toString();
transactionID = imeiCode + "" + dateTime;
if (spinnerData.equals("") || vehicleNo1.equals("")
|| spinnerAccountName.equals("")
|| spinnerFuelRate.equals("")
|| driverName.equals("")
|| dieselQty.equals("")
|| dieselRate.equals("")
|| amount.equals("")
|| referenceNo.equals("")) {
Toast.makeText(getBaseContext(),
"Please fill all the fields",
Toast.LENGTH_LONG).show();
}
else if (noOfCopies.equals("")) {
Toast.makeText(getBaseContext(),
"Please enter any value",
Toast.LENGTH_LONG).show();
} else {
long id = listHelper.insertPumpData(
acName, vehicleNo1,
driverName,driverCode,
dieselRate, dieselQty, amount + " Rs",
referenceNo, noOfCopies, date, time,
transactionID);
}
}
});
Thank You
Ok i myself got an answer to the above question
I did this to get the value of selected spinner item
Cursor acNameCur=(Cursor)spinnerAccountName.getSelectedItem();
String accountNamecol=acNameCur.getString(acNameCur.getColumnIndex
(DbListHelper.ACCOUNT_NAME));
Related
i want to change my listview item's Backgroundcolor but when I run it wont change and showing that index not found.
here i also checked that last if(sts.equals("true")) condition is matched or not, but also it matched successfully just color is not changing, it invokes the catch part and showing "Error in fetching data: null"
public void viewTask()
{
int i=0;
try{
Cursor c1 = myDB.rawQuery("SELECT * FROM "+TBName+" where Event_id= '" +Eid+ "'" , null);
String Data[] = new String[c1.getCount()+1];
if (c1 != null) {
c1.moveToFirst();
do {
Tname = c1.getString(c1.getColumnIndex("Task_name"));
sts= c1.getString(c1.getColumnIndex("Status"));
Data[i]=Tname;
item.add(Data[i]);
if(sts.equals("true"))
{
//Toast.makeText(getApplicationContext(),"Match",Toast.LENGTH_LONG).show();
lvProlist.getChildAt(i).setBackgroundColor(Color.GREEN);
}
i++;
}while(c1.moveToNext());
}
}
catch (Exception e) {
// TODO: handle exception
if(i>0){
Toast.makeText(getBaseContext(),
"Error in Fetching data: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getBaseContext(),
"PLEASE ADD TASK", Toast.LENGTH_LONG).show();
}
}
}
public View row;
your_list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v,
int position, long id) {
if (row != null) {
row.setBackgroundResource(R.color.orange);
}
row = v;
v.setBackgroundResource(R.color.transparent_green);
)};
Here : listview item background color change
Sorry for the mouthful of a title, I have to cut it down because I exceeded the 150 character limit.
I have an AutoCompleteTextView (ACTV) and I am using a SimpleCursorAdapter since the normal ACTV only searches the user input at the start of each substring (substring are separated by whitespaces) and not within those substrings. For example, having a list with Adipose and Bad Wolf and searching ad will show Adipose only and not Bad Wolf. I already made the Adapter as shown below:
//create ACTV Here
AutoCompleteTextView search = (AutoCompleteTextView) findViewById(R.id.actvCatalogueSearch);
search.setThreshold(1);
String[] from = { "name" };
int[] to = { android.R.id.text1 };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
cursorAdapter.setStringConversionColumn(1);
FilterQueryProvider provider = new FilterQueryProvider(){
#Override
public Cursor runQuery(CharSequence constraint) {
// TODO Auto-generated method stub
String constrain = (String) constraint;
constrain = constrain.toUpperCase();
Log.d("hi", "runQuery constraint: " + constraint);
if (constraint == null) {
return null;
}
String[] columnNames = { Columns._ID, "name" };
MatrixCursor c = new MatrixCursor(columnNames);
try {
for (int i = 0; i < pdflist.length; i++) {
if(pdflist[i].contains(constrain)){
Log.d("Hello","Match! pdflist item = " + pdflist[i]);
c.newRow().add(i).add(pdflist[i]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
};
cursorAdapter.setFilterQueryProvider(provider);
search.setAdapter(cursorAdapter);
This code enables me to show the other list items that contains the substring from the user input.
Now, I am trying to make the OnItemClickListener function properly. Here is what I have so far:
search.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
MatrixCursor matrix = (MatrixCursor)parent.getItemAtPosition(position);
Log.d("hello", "matrix values is = " + matrix);
String selection = matrix.getString(position);
Log.d("hallo","selection = " + selection);
Log.d("hello","item id at position = " + parent.getItemIdAtPosition(position));
int pos = (int) parent.getItemIdAtPosition(position);
Log.d("sup", "position is = " + pos);
String path = imagelist[pos].getAbsolutePath();
openPdfIntent(path);
}
});
Here, I am trying to get the MatrixCursor element at the given position. It works fine of the user selects the first 2 suggestions. However, when the user clicks the 3rd suggestion onwards, the application throws a CursorIndexOutOfBoundsException Requested Column: 2, # of columns: 2 Clicking on the logCat lines pointed me to the code String selection = matrix.getString(position);
I think that doing matrix.getString(position) causes the error since getString returns the value of the requested column as a String, and since there are only 2 columns, selecting a suggestion in the ACTV whose position (position as it is shown to the user, not the position of the said item in the list) is greater than 2 causes the code to screw up.
My question is, is there a better way to get the String value of the selected item given that I am using SimpleCursorAdapter? I've looked over the documentation of Matrix Cursor in the android dev site and I can't find a way to get a row/element based on the position.
Any help is very much appreciated.
Edit:
using matrix.moveToFirst(); as such did not help as well:
search.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
MatrixCursor matrix = (MatrixCursor)parent.getItemAtPosition(position);
if(matrix != null) {
if(matrix.getCount() > 0) {
matrix.moveToFirst();
String selection = matrix.getString(position);
int pos = (int) parent.getItemIdAtPosition(position);
String path = imagelist[pos].getAbsolutePath();
openPdfIntent(path);
}
}
}
});
and I still got the exception:
android.database.CursorIndexOutOfBoundsException: Requested column: 4, # of columns: 2
The requested column 4 is the position of the selected ACTV suggestion, indexed zero.
Try out like this
MatrixCursor matrix = .............
Log.d("hello", "matrix values is = " + matrix);
/***** Check here Cursor is NOT NULL *****/
if(matrix != null) {
if(matrix.getCount() > 0) {
matrix.moveToFirst();
/***
Your Stuff will be here....
**/
}
}
Made it work using a different approach. I get the View and cast it as a TextView. From there, I get the String input. I then use this string and look for its position in the original list. Note that my list is an Array, not an ArrayList, that's why I had to loop through all the items.
search.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView) view;
String userSelection = tv.getText().toString();
Log.d("hello", "selection is = " + userSelection);
int pos = -1;
for (int i = 0; i < pdflist.length; i++) {
if(pdflist[i].equalsIgnoreCase(userSelection)){
pos = i;
}
}
Log.d("hello","int position = " + pos);
String path = imagelist[pos].getAbsolutePath();
openPdfIntent(path);
}
});
I have done the following things in my program:
I am generating some Buttons programmatically in my MenuItemsActivity class. I have a Listview in the xml of the MenuItemsActivity class.
When I click on the button the appropriate contents get loaded in the Listview. I just refresh the activity i.e I am using the same Listview to load different contents based on the button which is clicked.
I want to do the following:
When the Button is clicked I want to change the background of the button to 'blue_tab` and maintain that same color when the same activity reloads. Can anyone guide me step by step what to do, as I am a newbie to Android.
i = getIntent();
String Salad=i.getStringExtra("Salad");
String cat_name_from_fragment=i.getStringExtra("category name");
final ListView salad_list = (ListView) findViewById(R.id.salads);
category = new ArrayList<HashMap<String, String>>();
items = new ArrayList<HashMap<String, String>>();
db = new DbHelper(MenuItemsActivity.this);
category.clear();
if (i.getStringExtra("category name") != null) {
String getcategory = i.getStringExtra("category name").toString();
items = db.retrieve_item_details(getcategory);
Log.i("sub items", "" + items);
}
else if(cat_name_from_fragment!=null)
{
items = db.retrieve_item_details(cat_name_from_fragment);
}
else
{
items = db.retrieve_item_details("Salads");
}
category = db.retrieve_category_name();
count = category.size();
Log.i("Sqlite database values", "" + count + " " + category);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
LinearLayout l1 = (LinearLayout) findViewById(R.id.tableRow1);
int i = 0;
for (HashMap<String, String> map : category)
for (Entry<String, String> mapEntry : map.entrySet()) {
String key = mapEntry.getKey();
String value = mapEntry.getValue();
TextView tv2 = new TextView(this);
tv2.setLayoutParams(new LinearLayout.LayoutParams(40, 90));
Log.i("map", "" + value);
final Button tv1 = new Button(this);
tv1.setId(i);
tv1.setText(value);
tv1.setTextSize(35);
tv1.setTextColor(Color.parseColor("#1569C7"));
tv1.setGravity(Gravity.CENTER);
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup));
tv1.setLayoutParams(new LinearLayout.LayoutParams(300,90));
tv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String text = tv1.getText().toString();
Log.e("text message", "" + text);
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
Toast.makeText(MenuItemsActivity.this, "clicked", 1000)
.show();
Intent i = new Intent(MenuItemsActivity.this,
MenuItemsActivity.class);
i.putExtra("category name", "" + text);
finish();
startActivity(i);
}
});
/*TextView tv2 = new TextView(this);
tv2.setText(" ");
tv2.setTextSize(10);
tv2.setGravity(Gravity.CENTER);*/
l1.addView(tv1);
l1.addView(tv2);
i++;
Log.e("i count ", "" + i);
}
final int imageArra[] = { R.drawable.leftbar_logo ,R.drawable.leftbar_logo};
ListAdapter k = new SimpleAdapter(MenuItemsActivity.this, items,
R.layout.menulist, new String[] { "Item_Name", "Desc",
"Currency", "Price","url","veggie","cat" }, new int[] { R.id.cat_name,
R.id.textView1, R.id.textView2, R.id.textView3,R.id.url,R.id.veggie,R.id.Category}) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final View v = super.getView(position, convertView, parent);
final ImageView im=(ImageView)v.findViewById(R.id.imageView1);
TextView url=(TextView)v.findViewById(R.id.url);
TextView veg=(TextView)v.findViewById(R.id.veggie);
String vegg=veg.getText().toString();
ImageView imagevegs=(ImageView)v.findViewById(R.id.veggies);
Log.i("veggie",""+vegg);
if(vegg.compareToIgnoreCase("Veg")==0)
{
imagevegs.setImageResource(R.drawable.veg);
imagevegs.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
else
{imagevegs.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imagevegs.setImageResource(R.drawable.non);
}
final String urls="http://166.62.17.208/"+url.getText().toString();
Log.i("urls",""+urls);
imageLoader.DisplayImage(urls,im);
//return super.getView(position, convertView, parent);
return v;
}
};
salad_list.setAdapter(k);
You can use PreferenceManager to save data and use it when the app is reloaded/restarted
sample:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String text = tv1.getText().toString();
Log.e("text message", "" + text);
if(PreferenceManager.getDefaultSharedPreferences(MenuItemsActivity.this).getString("button", "").length != 0)
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
else
{
Editor editor = PreferenceManager.getDefaultSharedPreferences(MenuItemsActivity.this).edit();
editor.putString("button", "1");
editor.commit();
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
}
Toast.makeText(MenuItemsActivity.this, "clicked", 1000)
.show();
Intent i = new Intent(MenuItemsActivity.this,
MenuItemsActivity.class);
i.putExtra("category name", "" + text);
finish();
startActivity(i);
}
EDITED
I am working on a contact list and trying to implement sectioned listview. When the app gets started, only one of the Header (Section) starts displaying itself after some chunks of items repeatedly and changing its position on scrolling up/down.
Here is my code :
private class MySimpleCursorAdapter extends SimpleCursorAdapter {
Holder holder = null;
LayoutInflater layoutInflater;
// String keyWord = "empty";
public MySimpleCursorAdapter(Context context, int layout, Cursor cur,
String[] from, int[] to, int flag) {
super(context, layout, cur, from, to, flag);
}
public String getTitle(String contName) {
return contName.substring(0, 1);
}
#Override
public View newView(Context context, Cursor mCursor, ViewGroup parent) {
holder = new Holder();
layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
String cont_Name = mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
View view = null;
if ( ! keyWord.equalsIgnoreCase(getTitle(cont_Name)) || keyWord.equals(null))
{
view = layoutInflater.inflate(R.layout.section_header, null);
TextView sectionTitle = (TextView) view.findViewById(R.id.title2);
sectionTitle.setText(getTitle(cont_Name));
keyWord = getTitle(cont_Name);
Log.d("KeyWord", keyWord);
Log.d("Contact Name", cont_Name);
}
else if(keyWord.equalsIgnoreCase(getTitle(cont_Name))) {
view = layoutInflater.inflate(R.layout.pm_fragment, null);
holder.contactTitle= (TextView)view.findViewById(R.id.textView1);
holder.contactDetail = (TextView)view.findViewById(R.id.textView2);
holder.contactTitle.setText(mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
holder.contactDetail.setText(mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
Log.d("KeyWord", keyWord);
Log.d("Contact Name", cont_Name);
String contactId_String = ""+mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
long contactId = Long.parseLong(mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)));
DatabaseHandler handler = new DatabaseHandler(getActivity());
Contact matchedContact = handler.getContact(contactId) ;
String dbContactId= "";
if(matchedContact != null){
if(matchedContact.getID() != 0 && ""+matchedContact.getID() != null){
dbContactId= ""+matchedContact.getID();
}
if(dbContactId.equals(contactId_String)){
holder.myImage = (ImageView) view.findViewById(R.id.imageView1);
holder.myImage.getLayoutParams().height = 100;
holder.myImage.getLayoutParams().width = 100;
holder.myImage.setBackgroundResource(R.drawable.person_empty_online);
}
}else{
holder.myImage = (ImageView) view.findViewById(R.id.imageView1);
holder.myImage.getLayoutParams().height = 100;
holder.myImage.getLayoutParams().width = 100;
holder.myImage.setBackgroundResource(R.drawable.person_empty_offline);
}
handler.close();
keyWord = getTitle(cont_Name);
}
return view;
}
}
During Debugging, After the ending line return view ; , it enters in CursorAdapter.class and passes by through the lines:
if (!mCursor.moveToPosition(position)) {
throw new IllegalStateException("couldn't move cursor to position " + position);
}
and enters in if condtion, but app doesn't crash.
Finally Got my answer my own after two weeks...my if-else conditions were too complex , so i make comparison on some different criteria.
if (mCursor.getPosition() > 0 && mCursor.moveToPrevious())
{
preName = mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
mCursor.moveToNext();
}
else if(mCursor.getPosition() == 0)
{
preName = null;
}
else{
preName = null;
}
if(preName != null){
preTitle = getTitle(preName);
}
//===============================================================================
/*
* Setting Header And Contact Details
*/
//===============================================================================
if(mCursor.isFirst()){
holder.titleText.setVisibility(View.VISIBLE);
holder.titleText.setText(itemTitle);
}
else if(preName != null){
if(! itemTitle.equalsIgnoreCase(preTitle))
{
holder.titleText.setVisibility(View.VISIBLE);
holder.titleText.setText(itemTitle);
}else{
holder.titleText.setVisibility(View.GONE);
}
}
holder.contactTitle.setText(mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
holder.contactDetail.setText(mCursor.getString(mCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
I have a problem that I have tried several different failed solutions for.
I have a AutoCompleteTextView with a SimpleCursorAdaptor tied to my database to pull the names of products. When a user searches for a product, the name shows up fine. It is when they click on the product that a NullPointerException comes up and crashes the app. And the funny thing is, it only happens on HTC Devices. My Samsung works, my buddies Motorola works, the Emulator works. Just not a HTC.
Here is the stack trace from a User submitted from the Android Market.
java.lang.NullPointerException
at enders.pos.test.PointOfSale$8.onItemClick(PointOfSale.java:571)
at android.widget.AutoCompleteTextView.onCommitCompletion(AutoCompleteTextView.java:921)
at com.android.internal.widget.EditableInputConnection.commitCompletion(EditableInputConnection.java:78)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:309)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:75)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3835)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
at dalvik.system.NativeStart.main(Native Method)
Line 571 is:
Cursor c = shop.getProdByName(text.getText().toString());
I believe that it the TextView text is returning null. But I am unsure why.
Below is part of class PointOfsale:
final int[] to = new int[] { android.R.id.text1 };
final String[] from = new String[] { "name" };
SimpleCursorAdapter Autoadapter =
new SimpleCursorAdapter(this,
android.R.layout.simple_dropdown_item_1line, null,
from, to);
textView = (AutoCompleteTextView) findViewById(R.id.autoproduct);
textView.setAdapter(Autoadapter);
textView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
TextView text = (TextView) view;
Cursor c = shop.getProdByName(text.getText().toString());
if(c != null){
if(c.getColumnIndex("_id") >= 0){
Product product = new Product();
product.setId(c.getInt(c.getColumnIndex("_id")));
product.setBarcode(c.getString(c.getColumnIndex("barcode")));
product.setName(c.getString(c.getColumnIndex("name")));
product.setDesc(c.getString(c.getColumnIndex("desc")));
product.setPrice(c.getFloat(c.getColumnIndex("price")));
product.setCat(c.getInt(c.getColumnIndex("catid")));
cart.AddProduct(product);
c.close();
}else{
alertbox("Not Found", "Product not found");
}
}else{
alertbox("Not Found", "Product not found");
}
textView.setText("");
((ProductAdapter) inventoryList.getAdapter()).notifyDataSetChanged();
}
});
Autoadapter.setCursorToStringConverter(new CursorToStringConverter() {
public String convertToString(android.database.Cursor cursor) {
// Get the label for this row out of the "state" column
final int columnIndex = cursor.getColumnIndexOrThrow("name");
final String str = cursor.getString(columnIndex);
return str;
}
});
// Set the FilterQueryProvider, to run queries for choices
// that match the specified input.
Autoadapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
// Search for states whose names begin with the specified letters.
Cursor cursor = ProductDatabase.helper.fetchItemsByName(
(constraint != null ? constraint.toString() : null));
return cursor;
}
});
Add a log at your code where you are getting the error and see if it's returning a value from the HTC device's Logcat. It's probably that there's a difference in handling the text view for that device.Do some system out to check if they are null or not.
System.out.println(text,text.getText().toString());
If it is returning a null for the HTC device only then you need to find a workaround for it's either your view hierarchy logic is wrong ( which seems okay here) or there's a bug for HTC devices.If that's the case pretty tough to solve then have good luck.
I have found a great solution to my problem! I have gotten rid of the SimpleCursorAdaptor and implemented my own method. I have also determined that several devices handles the UI differently. So i implemented a brute force method to get the data from 4 different methods. If one fails, it moves on to the next one. But one method should always get the data. Here is the code:
Autoadapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line);
Autoadapter.setNotifyOnChange(true);
textView = (AutoCompleteTextView) findViewById(R.id.autoproduct);
textView.setAdapter(Autoadapter);
textView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
boolean isAGo = false;
String item = null;
Cursor c = null;
if(listView != null){
item = listView.getItemAtPosition(position).toString();
c = shop.getProdByName(item);
isAGo = true;
}
if(isAGo == false){
if(view != null){
TextView text = (TextView) view;
c = shop.getProdByName(text.getText().toString());
isAGo = true;
}
}
if(isAGo == false){
if(textView.getText() != null){
item = textView.getText().toString();
c = shop.getProdByName(item);
isAGo = true;
}
}
if(isAGo == false){
if(prodList.length > 0){
item = prodList[0];
c = shop.getProdByName(item);
isAGo = true;
}
}
if(c != null){
if(c.getColumnIndex("_id") >= 0){
Product product = new Product();
product.setId(c.getInt(c.getColumnIndex("_id")));
product.setBarcode(c.getString(c.getColumnIndex("barcode")));
product.setName(c.getString(c.getColumnIndex("name")));
product.setDesc(c.getString(c.getColumnIndex("desc")));
product.setPrice(c.getFloat(c.getColumnIndex("price")));
product.setCat(c.getInt(c.getColumnIndex("catid")));
cart.AddProduct(product);
}else{
alertbox("Not Found", "Product not found");
}
}else{
alertbox("Error", "Unable to retrieve product.");
}
textView.setText("");
((ProductAdapter) inventoryList.getAdapter()).notifyDataSetChanged();
}
});
textView.addTextChangedListener(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)
{
prodList = ProductDatabase.helper.fetchItemsByName(s.toString());
if(prodList != null){
Autoadapter.clear();
for (int i = 0; i < prodList.length; i++)
{
Log.v("Items", "Item: " + prodList[i]);
Autoadapter.add(prodList[i]);
}
}else{
Autoadapter.clear();
}
}
});