I have a column in the database _id I would like to get this id when an list view item is clicked. Currently the code below is giving me the position of the item. I' am still playing around with it I have a feeling something is wrong in the method 'getItemId'
onCreate method
ArrayList<String> arrayCatNames = new ArrayList<String>();
String query = "SELECT * FROM category ORDER BY name ASC";
Cursor results = myDB.rawQuery(query, null);
while(results.moveToNext()){
String catName = results.getString(results.getColumnIndex("name"));
arrayCatNames.add(catName);
}
String[] catNamesArr = new String[arrayCatNames.size()];
catNamesArr = arrayCatNames.toArray(catNamesArr);
lvActivityCategory = (ListView) findViewById(R.id.lvActivityCategory);
lvActivityCategory.setAdapter(new categoryCursorAdaptor(this, catNamesArr));
lvActivityCategory.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), categoryActivity.class);
intent.putExtra("category_id", id);
Context context = getApplicationContext();
String s = Long.toString(position);
CharSequence text = s;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
categoryCursorAdaptor
class categoryCursorAdaptor extends BaseAdapter {
Context context;
String[] data;
private static LayoutInflater inflater = null;
public categoryCursorAdaptor(Context context, String[] data) {
this.context = context;
this.data = data;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.length;
}
#Override
public Object getItem(int position) {
return data[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (vi == null) vi = inflater.inflate(R.layout.item_category, null);
TextView text = (TextView) vi.findViewById(R.id.itemListCategory);
text.setText(data[position]);
return vi;
}
}
ArrayList<String> arrayCatNames = new ArrayList<String>();
ArrayList<Integer> arrayIds = new ArrayList<Integer>();
String query = "SELECT * FROM category ORDER BY name ASC";
Cursor results = myDB.rawQuery(query, null);
while(results.moveToNext()){
String catName = results.getString(results.getColumnIndex("name"));
int Ids = results.getInt(results.getColumnIndex("_id"));
arrayCatNames.add(catName);
arrayIds.add(Ids);
}
Then in your onItemClick
yourCategoryId = arrayIds.get(position);
You need to declare your ArrayList arrayIds at the top, before your onCreate
Related
I use SQLITE database to store list items and Baseadapter to display listview in my application.
Each item in the listview have edit text value, By default the value is 1.
When user changes the value from 1 to 2 , then the value has to be updated in database.
This update has to be done inside Adapter.
Below is the Adapter code where I change the edit text value.
public class CustomAdapter_cart extends BaseAdapter {
ArrayList<String> list_name = new ArrayList<String>();
ArrayList<String> list_price = new ArrayList<String>();
ArrayList<String> list_images = new ArrayList<String>();
ArrayList<String> list_model = new ArrayList<String>();
ArrayList<String> list_productid = new ArrayList<String>();
ArrayList<Integer> ids = new ArrayList<Integer>();
CustomAdapter_cart cart_refresh;
Bitmap b;
Context context;
AddToCart cart;
String value,name,price,image_new,model,product,qty;
private static LayoutInflater inflater = null;
Cursor cu;
String quant;
Holder holder = new Holder();
SharedPreferences sharedpreferences;
ArrayList<String>listMessages = new ArrayList<String>(new LinkedHashSet<String>());
ArrayList<String> quant_items = new ArrayList<String>();
Cursor mCursor;
ContentValues data=new ContentValues();
String model_item;
String id;
int id_final;
public CustomAdapter_cart(Context context, ArrayList<String> list_name, ArrayList<String> list_price, ArrayList<String> bitmapArray, ArrayList<String> list_model, ArrayList<String> list_productid,ArrayList<String> qty, ArrayList<Integer>ids ) {
this.context = context;
this.list_name = list_name;
this.list_price = list_price;
this.list_images = bitmapArray;
this.list_model = list_model;
this.list_productid = list_productid;
this.quant_items = qty;
this.cart_refresh = this;
this.ids = ids;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list_name.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView tv_name, tv_price, tv_model,tv_product,tv_id;
ImageView image;
Button delete;
EditText quantity;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View rowView = convertView;
if (convertView == null) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.list_items_cart, null);
holder.tv_name = (TextView) rowView.findViewById(R.id.name_cart);
holder.tv_price = (TextView) rowView.findViewById(R.id.price_cart);
holder.image = (ImageView) rowView.findViewById(R.id.image_cart);
holder.tv_model = (TextView) rowView.findViewById(R.id.model_cart);
holder.tv_product = (TextView) rowView.findViewById(R.id.product_cart);
holder.delete = (Button) rowView.findViewById(R.id.delete);
holder.quantity = (EditText) rowView.findViewById(R.id.quantity);
holder.tv_id = (TextView)rowView.findViewById(R.id.ids);
rowView.setTag(holder);
}
else
holder = (Holder) rowView.getTag();
holder.tv_name.setText(list_name.get(position));
name = holder.tv_name.getText().toString();
holder.tv_price.setText(list_price.get(position));
price = holder.tv_price.getText().toString();
holder.tv_model.setText(list_model.get(position));
model = holder.tv_model.getText().toString();
holder.tv_product.setText(list_productid.get(position));
product = holder.tv_product.getText().toString();
holder.quantity.setText(quant_items.get(position));
quant = holder.quantity.getText().toString();
holder.tv_id.setText(Integer.toString(ids.get(position)));
id = holder.tv_id.getText().toString();
id_final = Integer.parseInt(id);
holder.image.setImageBitmap(loadImageFromStorage(list_images.get(position)));
image_new = holder.image.toString();
final View finalRowView1 = rowView;
holder.quantity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
value = s.toString();
quant.replace(quant, value);
updateTable();
Toast.makeText(finalRowView1.getContext(), "Updating Table", Toast.LENGTH_SHORT).show();
}
});
final View finalRowView = rowView;
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name_item = ((TextView) finalRowView.findViewById(R.id.name_cart)).getText().toString();
String price_item = ((TextView) finalRowView.findViewById(R.id.price_cart)).getText().toString();
model_item = ((TextView) finalRowView.findViewById(R.id.model_cart)).getText().toString();
Intent in = new Intent(context, AddCart_FullImage.class);
in.putExtra("model", model_item);
in.putExtra("name", name_item);
in.putExtra("price", price_item);
context.startActivity(in);
}
});
return rowView;
}
private Bitmap loadImageFromStorage(String path) {
try {
File f = new File(path, "");
f.canRead();
b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
public void updateTable() {
final DatabaseHandler db = new DatabaseHandler(context);
SQLiteDatabase db1 = db.getWritableDatabase();
try {
db.updateContact(new Cart(id_final,name, price, image_new, model, product, value));
Log.v("LOG", "After text change value db " + value);
} catch (Exception e) {
}
}
}
Problem
When I try to update the edit text value, it gets updated in db but again it changes to default value "1".
I am not sure where I am going wrong.
Any help would be really greatfull.
Thanks.
Each time the system wants to redraw your ListView it calls the getView(...) method of your adapter. The following line sets the value of your quantity EditText:
holder.quantity.setText(quant_items.get(position));
When the user changes the value in the EditText you do the following:
quant.replace(quant, value);
updateTable();
As you can see, your adapter's datasource (quant_items) is not updated.
Since you are updating the database from within the adapter, you can just update the quant_items ArrayList and it should do the trick.
You need to notify your adapter if you change its data (and of, you need to update list_name with the new values).
The easiest way to notify your adapter is to use notifyDatasetChanged() after you updated your data.
I would like to ask some question about AdapterView.
In my application, there is an activity which retrieve data from database and display them in AdapterView.
However, when i install the application in different devices, I found that the part I have just mentioned could only function on some devices. The others cannot show the database results.
Here is my code:
private void showResults(String query) {
Cursor cursor = searchCustByInputText(query);
if (cursor == null) {
//
} else {
// Specify the columns we want to display in the result
String[] from = new String[] {
"cust_code",
"chinese_name"};
// Specify the Corresponding layout elements where we want the columns to go
int[] to = new int[] {
R.id.scust_code,
R.id.schinese_name};
// Create a simple cursor adapter for the definitions and apply them to the ListView
SimpleCursorAdapter customers = new SimpleCursorAdapter(this,R.layout.cust_list_item, cursor, from, to);
mListView.setAdapter(customers);
// Define the on-click listener for the list items
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor c = (Cursor) mListView.getItemAtPosition(position);
String cust_code = c.getString(c.getColumnIndex("cust_code"));
if (callFromAct.equals("Main")) {
String pay_term = c.getString(c.getColumnIndex("pay_term"));
String chinese_name = c.getString(c.getColumnIndex("chinese_name"));
String english_name = c.getString(c.getColumnIndex("english_name"));
String address_1 = c.getString(c.getColumnIndex("address_1"));
String address_2 = c.getString(c.getColumnIndex("address_2"));
String address_3 = c.getString(c.getColumnIndex("address_3"));
String address_4 = c.getString(c.getColumnIndex("address_4"));
String contact = c.getString(c.getColumnIndex("contact"));
String telephone = c.getString(c.getColumnIndex("telephone"));
String last_order_date = c.getString(c.getColumnIndex("last_order_date"));
//Pass data to another Activity
Intent it = new Intent(CustEnqActivity.this, CustEnqDetailsActivity.class);
Bundle bundle = new Bundle();
bundle.putString("cust_code", cust_code);
bundle.putString("pay_term", pay_term);
bundle.putString("chinese_name", chinese_name);
bundle.putString("english_name", english_name);
bundle.putString("address_1", address_1);
bundle.putString("address_2", address_2);
bundle.putString("address_3", address_3);
bundle.putString("address_4", address_4);
bundle.putString("contact", contact);
bundle.putString("telephone", telephone);
bundle.putString("last_order_date", last_order_date);
it.putExtras(bundle);
startActivity(it);
}
else {
returnToCallingAct(cust_code);
}
//searchView.setQuery("",true);
}
});
}
}
Besides, I discovered there were two warnings in my logcat.
The constructor SimpleCursorAdapter(Context, int, Cursor, String[], int[]) is deprecated
AdapterView is a raw type. References to generic type AdapterView should be parameterized
Are they related to the problem?
Try to create a class that extends BaseAdapter and use ViewHolders for performance
eg:
public class MyBaseAdapter extends BaseAdapter {
ArrayList<ListData> myList = new ArrayList<ListData>();
LayoutInflater inflater;
Context context;
public MyBaseAdapter(Context context, ArrayList<ListData> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context); // only context can also be used
}
#Override
public int getCount() {
return myList.size();
}
#Override
public ListData getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.layout_list_item, null);
mViewHolder = new MyViewHolder();
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
mViewHolder.tvTitle = detail(convertView, R.id.tvTitle, myList.get(position).getTitle());
mViewHolder.tvDesc = detail(convertView, R.id.tvDesc, myList.get(position).getDescription());
mViewHolder.ivIcon = detail(convertView, R.id.ivIcon, myList.get(position).getImgResId());
return convertView;
}
// or you can try better way
private TextView detail(View v, int resId, String text) {
TextView tv = (TextView) v.findViewById(resId);
tv.setText(text);
return tv;
}
private ImageView detail(View v, int resId, int icon) {
ImageView iv = (ImageView) v.findViewById(resId);
iv.setImageResource(icon); //
return iv;
}
private class MyViewHolder {
TextView tvTitle, tvDesc;
ImageView ivIcon;
}
}
More info/example:
http://www.pcsalt.com/android/listview-using-baseadapter-android/#sthash.lNGSCiyB.dpbs
I have a listview in my application.I want to set the value of textview in that particular row when I click one of the textview in that row itself.so,I tried like below
likes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView t=(TextView)v;
TextView likesnumber1 = (TextView) findViewById(R.id.likesnumber);
int i= Integer.parseInt(likescount.get(position));
if(like_or_ulike.get(position).equals("Like")){
Log.e("inlike","like");
like_or_ulike.set(position, "Unlike");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"post");
j=i+1;
String s=Integer.toString(j);
likescount.set(position, s);
likesnumber1.setText(likescount.get(position));
}
else{
Log.e("unlike","unlike");
like_or_ulike.set(position, "Like");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"DELETE");
j=i-1;
String s=Integer.toString(j);
likescount.set(position, s);
likesnumber1.setText(likescount.get(position));
}
}
});
the "likes" reference which I used is textview and I want to set the textview by getting the id of that particular row.
TextView likesnumber1 = (TextView) findViewById(R.id.likesnumber);
when I use this I am getting the id of the first visible row of the screen.
How can I get the id of textview of that particular row,on a textview click.
Thanks
I'm not sure how you are populating your list with data, however here is a method I use that works very well.
Data Models
public class Publication {
public String string1;
public String string2;
public Publication() {
}
public Publication(String string1, String string2) {
this.string1= string1;
this.string2= string2;
}
}
Create an array adapter
public class ContactArrayAdapter extends ArrayAdapter<ContactModel> {
private static final String tag = "ContactArrayAdapter";
private static final String ASSETS_DIR = "images/";
private Context context;
//private ImageView _emotionIcon;
private TextView _name;
private TextView _email;
private CheckBox _checkBox;
private List<ContactModel> contactModelList = new ArrayList<ContactModel>();
public ContactArrayAdapter(Context context, int textViewResourceId,
List<ContactModel> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.contactModelList = objects;
}
public int getCount() {
return this.contactModelList.size();
}
public ContactModel getItem(int index) {
return this.contactModelList.get(index);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
// ROW INFLATION
Log.d(tag, "Starting XML Row Inflation ... ");
LayoutInflater inflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.contact_list_entry, parent, false);
Log.d(tag, "Successfully completed XML Row Inflation!");
}
// Get item
final ContactModel contactModel = getItem(position);
Resources res = this.getContext().getResources();
//Here are some samples so I don't forget...
//
//_titleCount = (TextView) row.findViewById(R.id.category_count);
// _category.setText(categories1.Category);
//
//if (categories1.Category.equals("Angry")) {
//Drawable angry = res.getDrawable(R.drawable.angry);
//_emotionIcon.setImageDrawable(angry);
//}
_checkBox = (CheckBox) row.findViewById(R.id.contact_chk);
_email = (TextView) row.findViewById(R.id.contact_Email);
_name = (TextView)row.findViewById(R.id.contact_Name);
//Set the values
_checkBox.setChecked(contactModel.IsChecked);
_email.setText(contactModel.Email);
_name.setText(contactModel.Name);
_checkBox.setOnClickListener(new CompoundButton.OnClickListener() {
#Override
public void onClick(View view) {
if (contactModel.IsChecked) {
contactModel.IsChecked = false;
notifyDataSetChanged();
}
else {
contactModel.IsChecked = true;
notifyDataSetChanged();
}
}
});
return row;
}
}
Use the array adapter to fill your list
ContactArrayAdapter contactArrayAdapter;
//
List<ContactModel> contactModelList;
//Fill list with your method
contactModelList = getAllPhoneContacts();
//
contactArrayAdapter = new ContactArrayAdapter(getApplicationContext(), R.layout.contact_list_entry, contactModelList);
//
setListAdapter(contactArrayAdapter);
A sample method to fill data:
public List<ContactModel> getAllPhoneContacts() {
Log.d("START","Getting all Contacts");
List<ContactModel> arrContacts = new Stack<ContactModel>();
Uri uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, new String[] {ContactsContract.CommonDataKinds.Email.DATA1
,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
,ContactsContract.CommonDataKinds.Phone._ID}, null , null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
String email= cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
int phoneContactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
if (email != null)
{
ContactModel contactModel = new ContactModel();
contactModel.Name = name;
contactModel.Email = email;
contactModel.IsChecked = false;
arrContacts.add(contactModel);
}
cursor.moveToNext();
}
cursor.close();
cursor = null;
Log.d("END","Got all Contacts");
return arrContacts;
}
Accessing the data on click
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
//Click handler for listview
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
ContactModel contact= getItem(position);//This gets the data you want to change
//
some method here tochange set data
contact.email = "new#email.com"
//send notification
contactArrayAdapter.notifyDataSetChanged();
}
});
I'm trying to pass the item clicked to another activity i.e from A to B using a custom itemsAdapter with sqlite.
How can I achieve the following?
1)Get the item clicked position using cursor
2)Pass the item clicked to another activity
I'm trying to do similar to this example but use my own custom adapter
I have dome the following so far.
Activity A:
public void onListItemClick(ListView parent, View view, int position, long id) {
Intent intent = new Intent(this,F32Activity.class);
Cursor cursor = (Cursor) itemsAdapter.getItem(position);
intent.putExtra("PROPERTY_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
return;
}
Activity B:
propertyId = getIntent().getIntExtra("PROPERTY_ID", 0);
System.out.println(employeeId);
SQLiteDatabase db = (new Helper(this)).getWritableDatabase();
Cursor cursor = db
.rawQuery("SELECT * from my_table WHERE pro._id = ?",
new String[] { "" + propertyId });
Added the Adapter
private void getItemId(int position) {
// TODO Auto-generated method stub
}
private void getDataAndPopulate() {
// TODO Auto-generated method stub
image = new ArrayList<byte[]>();
bedrooms= new ArrayList<String>();
address= new ArrayList<String>();
propType= new ArrayList<String>();
Cursor cursor = getEvents(" gall,properties where properties._id = gall._id " );
while (cursor.moveToNext()) {
//String temp_id = cursor.getString(0);
byte[] temp_image = cursor.getBlob(2);
String temp_identifier = cursor.getString(1);
String temp_price = cursor.getString(3);
String temp_bedrooms = cursor.getString(4);
String temp_address = cursor.getString(5);
String temp_propType = cursor.getString(6);
image.add(temp_image);
//System.out.println(image);
bedrooms.add(temp_bedrooms);
address.add(temp_address);
propType.add(temp_propType);
}
String[] identifierArray = (String[]) bedrooms.toArray(new String[bedrooms
.size()]);
itemsAdapter = new ItemsAdapter(PropertyResult.this,
cursor, R.layout.activity_f9, identifierArray);
setListAdapter(itemsAdapter);
}
private class ItemsAdapter extends BaseAdapter {
String[] items;
public ItemsAdapter(Context context, Cursor cursor,int textViewResourceId,
String[] items) {
this.items = items;
}
public View getView(final int POSITION, View convertView,
ViewGroup parent) {
TextView desc;
TextView cap;
TextView ident;
TextView pric;
TextView bedroom;
TextView addres;
TextView propertytyp;
View view = convertView;
ImageView img;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.activity_f9, null);
}
img = (ImageView) view.findViewById(R.id.image);
bedroom = (TextView) view.findViewById(R.id.bedrooms);
addres = (TextView) view.findViewById(R.id.address);
propertytyp = (TextView) view.findViewById(R.id.propertytype);
bedroom.setText("£"+bedrooms.get(POSITION));
addres.setText(address.get(POSITION));
propertytyp.setText(propType.get(POSITION));
img.setImageBitmap(BitmapFactory.decodeByteArray(
image.get(POSITION), 0, image.get(POSITION).length));
return view;
}
public int getCount() {
return items.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
}
Please kindly give me a solution.
In the onListItemClick() you already have the row id from the cursor, is the 4th parameter, id(this only works for cursor adapters).
First of all also create and ArrayList that will hold long values(the row ids from the cursor):
ids = new ArrayList<Long>();
//...
while (cursor.moveToNext()) {
String temp_id = cursor.getString(0);// if 0 is your column containing the id(check it)
ids.add(temp_id);
//...
}
Then in your adapter override the method getItemId and return the long values from the ids ArrayList according to the position supplied:
public long getItemId(int position) {
return ids.get(position);
}
Then in your onListItemClick() simply use the id parameter:
public void onListItemClick(ListView parent, View view, int position, long id) {
Intent intent = new Intent(this,F32Activity.class);
intent.putExtra("PROPERTY_ID", id);
startActivity(intent);
}
Then in the receiving activity:
propertyId = getIntent().getLongExtra("PROPERTY_ID", 0);
Your on Item should like this
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
String strEventName, strEventDate;
int Id;
Cursor c = (Cursor) arg0.getAdapter().getItem(position);
intent.putExtra("PROPERTY_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);}
I am getting the data from sqlite database and trying to display it in CustomeListView But it is displaying some items example i can see six items in my listView at a time then it is showing six items when i scroll it, it will repeatedly show same items HERE IS MY CODE
Here i am querying from database
public ArrayList<GetEmailFromDatabase> emails_From_Database() {
SQLiteDatabase db = helper.getReadableDatabase();
try {
GetEmailFromDatabase gefd;
ArrayList<GetEmailFromDatabase> results = new ArrayList<GetEmailFromDatabase>();
Cursor c = db.rawQuery("select * from Emailreceived", null);
if (c.getCount() > 0) {
int i=0;
c.moveToPosition(i);
do {
gefd = new GetEmailFromDatabase();
gefd.setMessage_No(c.getInt(c.getColumnIndex("_Id")));
gefd.setFrom(c.getString(c.getColumnIndex("EmailFrom")));
gefd.setDate(c.getString(c.getColumnIndex("EmailDate")));
gefd.setSubject(c.getString(c.getColumnIndex("Subject")));
results.add(gefd);
gefd = null;
i++;
} while (c.moveToPosition(i));
c.close();
}
return results;
} finally {
if (db != null)
db.close();
}
}
This is my listActivity with custom list
public class Email_listActivity extends MenuOptions{
//Database getEmails = new Database(getApplicationContext());
String items[]={"red","white","Black","green","brown","yellow","blue","pink","orange"};
Database database;
String mData;
ArrayList<GetEmailFromDatabase> emailResults;
Database db1;
private EmailListFeedAdapter emailListFeedAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.email_list_main);
emailResults = new ArrayList<GetEmailFromDatabase>();
emailListFeedAdapter = new EmailListFeedAdapter(this, R.layout.email_listview_row, emailResults);
setListAdapter(this.emailListFeedAdapter);
getResults();
if(emailResults != null && emailResults.size() > -1){
emailListFeedAdapter.notifyDataSetChanged();
for(int i=0;i< emailResults.size();i++){
emailListFeedAdapter.add( emailResults.get(i));
Log.e("%%%%%%%%%%%%%%%%%%%", "emailResults -------->"+emailListFeedAdapter.areAllItemsEnabled());
}
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
int pos = position;
String s = (String) ((TextView) v.findViewById(R.id.item_number)).getText();
database = new Database(getApplicationContext());
mData = database.getDate(s);
Intent i = new Intent(Email_listActivity.this, EmailWebView.class);
i.putExtra("webData", mData);
startActivity(i);
Log.e("$$$$$$$$$$$$", "POSITION--------->"+position+" View-------->"+v);
Toast.makeText(getApplicationContext(), "Hello"+v, Toast.LENGTH_SHORT).show();
}
public void getResults(){
db1 = new Database(getBaseContext());
emailResults = new ArrayList<GetEmailFromDatabase>();
//ArrayList<GetEmailFromDatabase> fromdatabase = db1.emails_From_Database();
emailResults = db1.emails_From_Database();
}
public class EmailListFeedAdapter extends ArrayAdapter<GetEmailFromDatabase>{
private ArrayList<GetEmailFromDatabase> itemss;
public EmailListFeedAdapter(Context context, int textViewResourceId, ArrayList<GetEmailFromDatabase> items) {
super(context, textViewResourceId, items);
this.itemss = items;
}
#Override
public View getView(int position, View emailView, ViewGroup parent) {
if(emailView == null){
LayoutInflater inflater= (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
emailView= inflater.inflate(R.layout.email_listview_row, null);
GetEmailFromDatabase o = itemss.get(position);
if(o!=null){
TextView messageNo = (TextView)emailView.findViewById(R.id.item_number);
TextView subject= (TextView)emailView.findViewById(R.id.emaillistrow_txt_partofemail);
TextView sender= (TextView)emailView.findViewById(R.id.emaillistrow_txt_sender);
TextView datetime= (TextView)emailView.findViewById(R.id.emaillistrow_txt_datetime);
ImageView icon= (ImageView)emailView.findViewById(R.id.emaillistrow_icon_indicator);
icon.setImageResource(R.drawable.y_icon);
if(messageNo!=null){
messageNo.setText(Integer.toString(o.getMessage_No()));
}
if(subject!=null){
subject.setText(o.getSubject());
}
if(sender!=null){
sender.setText(o.getFrom());
}
if(datetime!=null){
datetime.setText(o.getDate());
}
}
}
return emailView;
}
}
}
Ok, can you replace your adapter class's getView() method with mine,
#Override
public View getView(int position, View emailView, ViewGroup parent) {
if(emailView == null){
LayoutInflater inflater= (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
emailView= inflater.inflate(R.layout.email_listview_row, null);
}
GetEmailFromDatabase o = itemss.get(position);
if(o!=null){
TextView messageNo = (TextView)emailView.findViewById(R.id.item_number);
TextView subject= (TextView)emailView.findViewById(R.id.emaillistrow_txt_partofemail);
TextView sender= (TextView)emailView.findViewById(R.id.emaillistrow_txt_sender);
TextView datetime= (TextView)emailView.findViewById(R.id.emaillistrow_txt_datetime);
ImageView icon= (ImageView)emailView.findViewById(R.id.emaillistrow_icon_indicator);
icon.setImageResource(R.drawable.y_icon);
if(messageNo!=null){
messageNo.setText(Integer.toString(o.getMessage_No()));
}
if(subject!=null){
subject.setText(o.getSubject());
}
if(sender!=null){
sender.setText(o.getFrom());
}
if(datetime!=null){
datetime.setText(o.getDate());
}
}
return emailView;
}
after replacing let me know what happen..