I've converted a list project from a BaseAdapter to an ArrayAdapter ListActivity because I was told in another question that ArrayAdapter was more dynamic and better at, specifically, allowing an item to be removed from the list and then updating to reflect that removal. I'm still running into the same issue with my ArrayAdapter, though, as follows:
I get my list data as so:
public void loadAdapter(){
DatabaseHelper helper = new DatabaseHelper(ActivityMain.this);
database = helper.getReadableDatabase();
Cursor data = database.query("list_data", fields, null, null, null,
null, null);
Integer tindex = data.getColumnIndex("listTitle");
Integer iindex = data.getColumnIndex("listType");
itemCount = 0;
for (data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
m_parts.add(new Item(data.getString(tindex), data.getString(iindex)));
itemCount++;
}
data.close();
for (int j = 0; j < 10; j++) {
m_parts.add(new Item("", "R"));
}
m_adapter = new ItemAdapter(ActivityMain.this, R.layout.listview, m_parts);
setListAdapter(m_adapter);
}
with this custom adapter:
public class ItemAdapter extends ArrayAdapter<Item> {
private ArrayList<Item> objects;
public ItemAdapter(Context context, int textViewResourceId,
ArrayList<Item> objects) {
super(context, textViewResourceId, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.listview, null);
}
Item i = objects.get(position);
if (i != null) {
TextView textview = (TextView) v.findViewById(R.id.tv_main);
ImageView imageview = (ImageView) v.findViewById(R.id.iv_main);
TextView textview2 = (TextView) v.findViewById(R.id.tv_main2);
textview.setText(i.getText());
textview2.setText(i.getText());
imageview.setScaleType(ScaleType.FIT_XY);
Integer theDrawable;
if (i.getImage() != "L") {
theDrawable = R.drawable.listview_regular;
} else {
theDrawable = R.drawable.listview_location;
}
imageview.setImageResource(theDrawable);
}
v.setOnClickListener(new OnItemClickListener(position));
v.setOnLongClickListener(new OnItemLongClickListener(position));
return v;
}
}
The context menu from longclicklistener offers a delete option, which uses this
private void showDialogOnLongClick(final int position) {
Builder alert = new AlertDialog.Builder(this);
ArrayList<String> listInfo = getListInfo(position);
String content = listInfo.get(1);
String numItems = "";
if (content != null && content.indexOf("|~|") > -1) {
String[] contentSplit = content.split("\\|\\~\\|");
numItems = contentSplit.length + " items in list";
} else {
numItems = "No items in list";
}
String listTitle = listInfo.get(0);
String created = "Created: " + listInfo.get(2);
String modified = "Modified: " + listInfo.get(3);
String delete = "Delete";
String edit = "Edit";
final String[] items = new String[] { created, modified, numItems,
delete, edit };
alert.setTitle(listTitle);
alert.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 3:
if (deleteList(position)) {
//listview.invalidate();
//Item itemToRemove = m_parts.remove(position);
//m_adapter.remove(itemToRemove);
//m_adapter.remove(toRemove);
//m_adapter.notifyDataSetInvalidated(); <-- These are all things I've tried
//m_adapter.clear(); in various combinations
//m_adapter.remove(position);
Item toRemove = m_adapter.getItem(position);
m_parts.remove(toRemove); //or, m_parts.remove(position);<-This is what should work
m_adapter.notifyDataSetChanged();
loadAdapter();
// runOnUiThread(new Runnable() {
// public void run() {
// m_adapter.notifyDataSetChanged(); <--I've tried a thread approach
// }
// });
}
break;
case 4:
Intent i = new Intent(ActivityMain.this,
ShowARegularList.class);
i.putExtra("list_id", (position + 1) + "");
startActivity(i);
break;
}
}
});
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
which, in case 3 changes the database with
// Delete single list item data
public boolean deleteList(int id) {
id++;
DatabaseHelper helper = new DatabaseHelper(this);
database = helper.getWritableDatabase();
// ContentValues values = new ContentValues();
// values.put("_id", id);
database.delete("list_data", "_id =" + id, null);
database.close();
// text = text.removeElementStr();
// itemCount--;
return true;
}
The above works to remove an item from the list, and closes the gap visually. But, when clicking on the "old" spot from which the item was removed (which raises a new intent to edit the selected item), an exception is raised in the new activity on querying the db (last line, 97 in logcat):
final Integer thisListID = Integer.parseInt(listIDstr);
final DatabaseHelper helper = new DatabaseHelper(this);
database = helper.getReadableDatabase();
Cursor cursor = database.query("list_data", new String[] { "listTitle",
"listContent", "dateCreated", "dateModified" }, "_id = " + thisListID
+ "", null, null, null, null);
ArrayList<String> listInfo = new ArrayList<String>();
if (cursor != null && cursor.moveToFirst()) {
listInfo.add(cursor.getString(cursor.getColumnIndex("listTitle")));
listInfo.add(cursor.getString(cursor.getColumnIndex("listContent")));
listInfo.add(cursor.getString(cursor.getColumnIndex("dateCreated")));
listInfo.add(cursor.getString(cursor.getColumnIndex("dateModified")));
}
cursor.close();
strListContent = listInfo.get(1).trim();
with logcat
java.lang.RuntimeException: Unable to start activity...
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2049)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2083)
at android.app.ActivityThread.access$600(ActivityThread.java:134)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1233)
...
at com.baked.listanywhere.ShowARegularList.onCreate(ShowARegularList.java:97)
The list items with index less than the deleted one are fine; those with greater index are one off in their contents. I suspect an error in logic on my part in the query, querying an index that is no longer there...but it seems I should be able to redraw the list and have an index list that mirrors the database. What I would truly like to do is extinguish any memory of the list and then refill it, but I can't seem to do this...any help would be much appreciated!
Well, as no one is chiming in, I've resolved the issue by querying
Cursor cursor = database.rawQuery("SELECT * FROM list_data ORDER BY _id LIMIT 1 OFFSET '"+ thisListID +"'", null);
thanks to Wojtek at this question. And, yes,
case 3:
if (deleteList(position)) {
Item toRemove = m_adapter.getItem(position);
m_parts.remove(toRemove);
m_adapter.notifyDataSetInvalidated();
loadAdapter();
break;
}
was working fine, even though I could have sworn that was the issue!
Related
I have a listview with data using customAdapter.class now what i want is that to transfer checked items in listview to secondActivity on button click...
btest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<Model> mylist = new ArrayList<Model>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
// listView = new ArrayList<Model>();
mylist.add(String.valueOf(adapter.getItem(position)));
}
String[] output = new String[mylist.size()];
for (int i = 0; i < mylist.size(); i++) {
output[i] = (mylist.get(i));
}
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
Bundle b = new Bundle();
b.putStringArray("selectedItems", output);
// b.putStringArrayList("SelectedItems: ",list);
// b.putString("selectedItems", String.valueOf(output));
intent.putExtras(b);
startActivity(intent);*/
}
});
and this is the second activity where i am getting that data in another listview
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
Bundle b = getIntent().getExtras();
String[] result = b.getStringArray("selectedItems");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, result);
lv.setAdapter(adapter);
}
The method you followed to send custom list to another activity will not work. In order to transfer your custom list between activities you need to create Parcelable List and send it through intent.
Android Intents does not support custom list.
Custom list can be passed in two ways, Serialization and Parcelable.
But Parcelable is more Efficient and Simple to implement.
Refer this link to send custom list between activities through Parcelable
This link will give you much better idea to implement Parcelable.
Updated Code: Change your Model Code like below.
public class Model implements Parcelable{
private String name;
private int selected;
public Model(String name){
this.name = name;
selected = 0;
}
public String getName(){
return name;
}
public int isSelected(){
return selected;
}
public void setSelected(boolean selected){
this.selected = selected;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
/**
* Storing the Student data to Parcel object
**/
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(selected);
}
private Model (Parcel in){
this.name = in.readString();
this.selected = in.readInt();
}
public static final Parcelable.Creator<Model> CREATOR = new Parcelable.Creator<Model>() {
#Override
public Student createFromParcel(Parcel source) {
return new Student(source);
}
#Override
public Model[] newArray(int size) {
return new Model[size];
}
};
}
Then in the MainActivity do this..
Intent next = new Intent(MainActivity , ResultActivity.class);
next.putParcelableArrayListExtra("model_data", (ArrayList<? extends Parcelable>) selectedItems);
startActivity(next);
In the ResultActivity do this.
ArrayList<Model> his = getIntent().getParcelableArrayListExtra("model_data");
Try the above code..
Good Luck..!!
i solve by saving checked items from listview to sqlite on button click. another button to open new activity and call selected items sqlite this way...
oncheckchange add and remove items in an arraylist and call this in onbutton click like this way...
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view = null;
Support support = (Support) this.getItem(position);
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.view_items, null);
view = new ViewHolder();
view.tvInfo = (TextView) convertView.findViewById(R.id.tvInfo);
view.cb = (CheckBox) convertView.findViewById(R.id.cb);
convertView.setTag(view);
view.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CheckBox cb = (CheckBox) buttonView;
Support support = (Support) cb.getTag();
support.setSelected(cb.isChecked());
if (isChecked){
selList.add(support.status);
selID.add(support.id);
selType.add(support.type);
// Toast.makeText(CustomAdapter.this, "Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked(), Toast.LENGTH_LONG).show();
}else {
selList.remove(support.status);
selID.remove(support.id);
selType.remove(support.type);
}
}
});
}else{
view = (ViewHolder) convertView.getTag();
view.cb = view.getCb();
view.tvInfo = view.getTvInfo();
}
view.cb.setTag(support);
support = list.get(position);
String id = support.getId();
String status = support.getStatus();
String type = support.getType();
view.cb.setChecked(support.isSelected());
// view.tvInfo.setText(id + "," + status + "," + type);
view.tvInfo.setText(status);
return convertView;
}
this is button coding to add to db
btest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.addSelected(adapter.selList, adapter.selID, adapter.selType);
and this is how to insert to sqlite..
public void addSelected(ArrayList<String> selList, ArrayList<String> selID, ArrayList<String> selType) {
int size = selID.size();
SQLiteDatabase db = getWritableDatabase();
try{
for (int i = 0; i < size ; i++){
ContentValues cv = new ContentValues();
// cv.put(KEY_ID, selID.get(i).toString());
cv.put(KEY_ID, selID.get(i));
cv.put(KEY_STATUS, selList.get(i));
cv.put(KEY_TYPE, selType.get(i));
Log.d("Added ",""+ cv);
db.insertOrThrow(TABLE_SELECTED, null, cv);
}
db.close();
}catch (Exception e){
Log.e("Problem", e + " ");
}
}
and get back from db like this
public ArrayList<String> getSelected() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> result = null;
try{
result = new ArrayList<String>();
// String query = "SELECT * FROM " + TABLE_SELECTED;
String query = "SELECT " + KEY_ID + " FROM " + TABLE_SELECTED;
Cursor c = db.rawQuery(query, null);
if (!c.isLast()){
if (c.moveToFirst()){
do{
String sel_name = c.getString(c.getColumnIndex("_id"));
result.add(sel_name);
Log.d("Added ", sel_name);
}while (c.moveToNext());
}
}
c.close();
db.close();
}catch (Exception e){
Log.e("Nothing is to show", e + " ");
}
return result;
}
I have several markers on a google map and in each marker a ListView with several entries.
Each entry can be liked by the user and if he has liked, there is stored an entry in the SQLite Database with the marker ID, the entry ID and if he has liked (1) or took the like back (0) and the activity is reloaded.
Now I want a filled heart to be shown below each List Item the user has liked. The problem is: Especially if there are many entries, there are randomly filled hearts, even if the user only liked one entry. These falsely filled hearts sometimes appear only at scrolling up so I assume, that the ListView does not update its elements at scrolling...
Here is my code:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ListCell cell;
if (convertView == null) {
convertView = inflater.inflate(R.layout.pinboard_list_view_cell, null);
cell = new ListCell();
cell.likes = (TextView) convertView.findViewById(R.id.listViewLikes);
cell.note = (TextView) convertView.findViewById(R.id.listViewNote);
cell.img = (ImageView) convertView.findViewById(R.id.listViewImg);
cell.likeImage = (ImageView) convertView.findViewById(R.id.heartImage);
convertView.setTag(cell);
}
else {
cell = (ListCell)convertView.getTag();
}
cell.position = position;
//Listen-Items mit entsprechenden Elementen aus dem heruntergeladenen Array befüllen
try {
JSONObject jsonObject = this.dataArray.getJSONObject(position);
cell.likes.setText(jsonObject.getString("likes"));
cell.note.setText(jsonObject.getString("note"));
cell.entryID = jsonObject.getString("id");
String img = jsonObject.getString("image");
String urlForImageInServer = baseUrlForImage + img;
Picasso.with(context)
.load(urlForImageInServer)
.placeholder(R.drawable.progress_animation)
.error(R.drawable.no_picture)
.into(cell.img);
objectID = ""+cell.entryID;
dbh = new DbHelper(context);
cursor = getLikes(dbh);
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
if (Integer.parseInt(cursor.getString(2)) == 1) {
cell.likeImage.setImageResource(R.drawable.heart_filled);
}
else {
cell.likeImage.setImageResource(R.drawable.heart);
}
}
while(cursor.moveToNext());
}
else {
cursor.close();
}
cursor.close();
}
catch (JSONException e) {
e.printStackTrace();
}
return convertView;
}
public static class ListCell {
private TextView likes;
private TextView note;
private ImageView img;
public ImageView likeImage;
public int position;
public String entryID;
}
public Cursor getLikes(DbHelper dbh) {
dbase = dbh.getReadableDatabase();
String columns[] = {dbh.LIKES_MARKERID, dbh.LIKES_ENTRYID, dbh.LIKES_LIKE};
String selection = dbh.LIKES_MARKERID + " LIKE ? AND " + dbh.LIKES_ENTRYID + " LIKE ? ";
String args[] = {markerID.toString(), objectID};
Cursor cursor = dbase.query(dbh.TABLE_LIKES, columns, selection, args , null, null, null, null);
return cursor;
}
if there are no likes make sure you set disable heart image explictly. Right now it seems you are trying to set it inside do while loop, if flow doesn't goes inside this loop, recycled view will be used which may or may not have disabled heart.
i am new to android, how to get phone numbers of selected contacts from MultiAutocompleteTextview when clicks on button ?
method to read contacts for multi-autocomplete textview
private void readContactData() {
// TODO Auto-generated method stub
String phoneNumber = "";
String phoneName = "";
phoneValueArr.clear();
nameValueArr.clear();
try{
ContentResolver content = getContentResolver();
cursor = content.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
PEOPLE_PROJECTION, null, null, null);
if(null != cursor && cursor.moveToFirst()){
do{
// Get Phone number
phoneNumber =""+cursor.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneName = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
phoneValueArr.add(phoneNumber.toString());
nameValueArr.add(phoneName.toString());
}while(cursor.moveToNext());
}
//cursor.close();
}catch(Exception e){
Log.i("AutocompleteContacts","Exception : "+ e);
}finally {
//if (null != cursor)
//cursor.close();
}
ContactListAdapter adapter = new ContactListAdapter(this, cursor);
mAuto.setAdapter(adapter);
}
my ContactsListAdapter
public static class ContactListAdapter extends CursorAdapter implements Filterable {
public ContactListAdapter(Context context, Cursor c) {
super(context, c);
mContent = context.getContentResolver();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final LayoutInflater inflater = LayoutInflater.from(context);
View retView = inflater.inflate(R.layout.schedule_msg_custcontview,parent,false);
return retView;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
//((TextView) view).setText(cursor.getString(2));
TextView pname = (TextView)view.findViewById(R.id.ccontName);
TextView pnum = (TextView)view.findViewById(R.id.ccontNo);
pname.setText(cursor.getString(2));
pnum.setText(cursor.getString(1));
}
#Override
public String convertToString(Cursor cursor) {
return cursor.getString(2);
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
if (getFilterQueryProvider() != null) {
return getFilterQueryProvider().runQuery(constraint);
}
StringBuilder buffer = null;
String[] args = null;
if (constraint != null) {
buffer = new StringBuilder();
buffer.append("UPPER(");
buffer.append(ContactsContract.Contacts.DISPLAY_NAME);
buffer.append(") GLOB ?");
args = new String[] { constraint.toString().toUpperCase() + "*" };
}
return mContent.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PEOPLE_PROJECTION,
buffer == null ? null : buffer.toString(), args,
null);
}
private ContentResolver mContent;
}
private static final String[] PEOPLE_PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.Contacts.DISPLAY_NAME,
};
and how can i get my selected contact numbers into an object to store in database while pressing the button. And while loading contacts its giving an exception saying that
12-11 12:39:11.422: I/AutocompleteContacts(17735): Exception : android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 188
can any one help me ?
This is my multi auto complete OnItemClick Listener and its always giving index of selected name index -1
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
// Get Array index value for selected name
int i = nameValueArr.indexOf(""+parent.getItemAtPosition(position));
// If name exist in name ArrayList
if (i >= 0) {
// Get Phone Number
toNumberValue = phoneValueArr.get(i);
InputMethodManager imm = (InputMethodManager) getSystemService(
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
// Show Alert
Toast.makeText(getBaseContext(), "Position:"+position+" Name:"+parent.getItemAtPosition(position)+" Number:"+toNumberValue,
Toast.LENGTH_LONG).show();
Log.d("AutocompleteContacts", "Position:"+position+" Name:"+parent.getItemAtPosition(position)+" Number:"+toNumberValue);
}
}
I solved the multi-autocomplete OnItemclickListener issue by changing the code as below
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
TextView temp = (TextView) view.findViewById(R.id.ccontNo);
TextView temp2 = (TextView) view.findViewById(R.id.ccontName);
final String selectedNumber = temp.getText().toString();
final String selectedName = temp2.getText().toString();
if (selectedNumber != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
// Show Alert
Toast.makeText(getBaseContext(), " Name:"+selectedName+" Number:"+selectedNumber, Toast.LENGTH_LONG).show();
}
}
Now i am getting the selected contact name and number. Then store those values in HashMap and while button click split the selected contacts by "," and iterate the loop for each name to get the contact number.
In this way i solved my problem hope it is helpful !! if so up Vote the answer!!!
im a newbie to android and i have this problem here hope you guys can help me with this :)
anyways, i want to get the id of a selected item in the spinner from sqlite database so that i can save it to another table later on.
here's my code:
in my DB.java :
public List<String> getSemesterList() {
List<String> List = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_SEMESTER;
Cursor c = ourDatabase.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
List.add((c.getString(1)));
} while (c.moveToNext());
}
return List;
}
public String getSemesterId() {
String[] columns = new String[] { KEY_SEMESTER_ID, KEY_SEMESTER };
Cursor c = ourDatabase.query(TABLE_SEMESTER, columns, null, null, null, null, null, null);
int id = c.getColumnIndex(KEY_SEMESTER_ID);
String semId = "";
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
semId = semId + c.getInt(id) + " "
+ "\n";
}
return semId ;
}
and in my createSYAttended.class
// TODO Auto-generated method stub
DB entry = new DB(this);
entry.open();
final List<String> all = entry.getSemesterList();
if(all.size()>0) // check if list contains items.
{
sqlSem = (Spinner) findViewById(R.id.sprSemester);
arrayAdapter = new ArrayAdapter<String>(CreateSyAttended.this,android.R.layout.simple_spinner_dropdown_item, all);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sqlSem.setAdapter(arrayAdapter);
entry.close();
sqlSem.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
} }
use a mapping for the index of your List<String> all = entry.getSemesterList(); to the spinner item
so when you get below callback
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
you can then use the position you get in the callback to map to the item in the semesterList all
I have an External Database into assets folder. I have been successful into loading it on my Emulator and performing operations on it.
I also know how to fill data using queries in Spinner and ListView.
The main issue: I am running a query which gives me all data from the table. I store them in a Bean class. Now i have successfully filled one of the column data into a spinner.
BUT, when i open the spinner, i don't get Database values but object name into spinner
FOR e.g -- com.mypackageName.BeanPackage.BeanClass#411da123
I get the whole spinner full of this, not the Data which is in Database( e.g 13, 13/1) .
My Code :
Query in DBHelper Class :
public Cursor getBusNumbers() {
// date="21-10-2013";
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
return db.rawQuery("select * from table", null);
}
In My Main Activity :
Adapter code :
adapter = new Adapter(MainActivity.this,android.R.layout.simple_spinner_item, array);
route.setAdapter(adapter);
adapter.notifyDataSetChanged();
My GetView method:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = ((LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(layout, null);
}
final Bean item = items.get(position);
final TextView km = (TextView) convertView
.findViewById(android.R.id.text1);
km.setText(item.getRouteNumber());
km.setTextSize(22);
return convertView;
}
}
Method which fills the Array :
private void loadFieldDatabase() {
Cursor c = dbhelper.getBusNumbers();
if (c != null && c.getCount() > 0) {
c.moveToFirst();
for (int count = 0; count < c.getCount(); count++) {
Bean detail = new Bean();
detail.setRouteNumber(c.getString(c
.getColumnIndex("route_number")));
array.add(detail);
c.moveToNext();
}
c.close();
//dbhelper.close();
}
Here in your code your setting the Bean object into the Text view insted of which item you need to set that.
Try this code this may help you.
private void loadSpinnerCourse() {
// TODO Auto-generated method stub
List<String> lables = getAllCourse();
// Creating adapter for spinner
dataAdapterCourse = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapterCourse
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
mLesson_course.setAdapter(dataAdapterCourse);
}
private List<String> getAllCourse() {
// TODO Auto-generated method stub
List<String> labels = new ArrayList<String>();
mCoureseIdList = new ArrayList<String>();
ExamDatabaseConnector dbConnector = new ExamDatabaseConnector(
getActivity());
dbConnector.open();
String selectQuery = "SELECT * FROM courses_stud";
Cursor cursor = dbConnector.database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
mCoureseIdList.add(cursor.getString(0));
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
dbConnector.database.close();
// returning lables
return labels;
}
Cursor cursor = db.getAllBhashat();
SpinnerArr = new String[cursor.getCount()+1];
SpinnerArr[0] = "<-SELECT->";
if(cursor.moveToNext()){
int i = 1;
do {
SpinnerArr[i] = cursor.getString(cursor
.getColumnIndex("LocalityTitle_E"));
i++;
} while (cursor.moveToNext());
}if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
ArrayAdapter<String> adapter_sorCat = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, SpinnerArr);
Spinner.setAdapter(adapter_sorCat);
adapter_sorCat
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}