Reputation: 2436
Hello friend i want to set selection() in spinner as per SQlite databse id so my cod eis as below
ArrayList<ParserCategory>mArrayListParserCategories = new ArrayList<ParserCategory>();
mArrayListParserCategories = mDatabaseConnectionAPI.getCategoryData(mStrinGetTrMode);
mSpinnerAdapterData = new SpinnerAdapterData(mArrayListParserCategories);
mSpinnerCate.setAdapter(mSpinnerAdapterData);
int id= mSpinnerCate.getIndexFromElement(mSpinnerAdapterData,mStringGetCantname);
DatabaseConnectionAPI.java
public ArrayList<ParserCategory> getCategoryData(String type) {
ArrayList<ParserCategory> mGetCategoryList = new ArrayList<ParserCategory>();
try {
String sqlQuery = "SELECT * FROM Category_Master where cat_type like "+ "'"+type+"'";
Cursor mCursorCategory = Query(sqlQuery);
if (mCursorCategory != null) {
mCursorCategory.moveToFirst();
while (!mCursorCategory.isAfterLast()) {
ParserCategory mParserCategory = new ParserCategory();
mParserCategory
.setCatId(mCursorCategory.getString(mCursorCategory
.getColumnIndex("cat_id")));
mParserCategory
.setCatName(mCursorCategory.getString(mCursorCategory
.getColumnIndex("cat_name")));
mParserCategory
.setCatType(mCursorCategory.getString(mCursorCategory
.getColumnIndex("cat_type")));
mParserCategory
.setCatMode(mCursorCategory.getString(mCursorCategory
.getColumnIndex("cat_mode")));
mGetCategoryList.add(mParserCategory);
mCursorCategory.moveToNext();
}
}
mCursorCategory.close();
} catch (Exception e) {
e.printStackTrace();
}
return mGetCategoryList;
}
SpinnerAdapterData.java
public class SpinnerAdapterData extends ArrayAdapter<ParserCategory> {
ArrayList<ParserCategory> mArrayList;
LayoutInflater mInflater;
Activity mActivity;
public SpinnerAdapterData(ArrayList<ParserCategory> list) {
super( IncomeUpdateActivity.this, R.layout.custom_spin_layout, list);
this.mArrayList = list;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflator = getLayoutInflater();
convertView = inflator.inflate(R.layout.custom_spin_layout, null);
TextView mTextView = (TextView) convertView.findViewById(R.id.txt);
mTextView.setText(mArrayList.get(position).getCatName());
return convertView;
}
}
getIndexFromElement Function
public int getIndexFromElement(ArrayAdapter<ParserCategory> adapter, String element) {
for(int i = 0; i < adapter.getCount(); i++) {
if(adapter.getItem(i).equals(element)) {
return i;
}
}
return 0;
}
When i run above code it retruns id always 0 any idea how can i solve it?
Upvotes: 0
Views: 301
Reputation: 8516
Your adapter contains ParserCategory
objects, and you are comparing them to String
parameter, which is always false. You probably want something like this (assuming the element should match the CatName field):
if (((ParserCategory)adapter.getItem(i)).getCatName().equals(element))
Another solution is overriding equals()
and hashCode()
in ParserCategory class.
Upvotes: 1