add data before sending in android dynamic listview - android

I have dynamic listview activity it transfer the item to another activity that have edit text(name,phone,table) and another dynamic listview under that.
the each item have edit text it should send with each item.
public class OrderAdapter extends BaseAdapter {
private Context ctx;
private LayoutInflater mInflater;
private List<Item> orderItems;
private DatabaseHelper helper;
public OrderAdapter(Context context, List<Item> items) {
// TODO Auto-generated constructor stub
ctx = context;
helper = new DatabaseHelper(ctx);
mInflater = LayoutInflater.from(ctx);
orderItems = items;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return orderItems.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return orderItems.get(position).getItemID();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public class ViewHolder {
TextView name, desc, price, total;
EditText etQty;
Button btnDelete, btnAdd, btnMinus;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.order_preview_row, parent,
false);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.c_table);
holder.desc = (TextView) convertView.findViewById(R.id.order_item_name);
holder.price = (TextView) convertView.findViewById(R.id.tvOpPrice);
holder.etQty = (EditText) convertView.findViewById(R.id.etQty);
holder.btnAdd = (Button) convertView
.findViewById(R.id.btnIncreaseQty);
holder.btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
float total_qty = (Float.parseFloat(holder.etQty.getText()
.toString()) + 1);
Item item = (Item) holder.etQty.getTag();
item.setNoItems(String.valueOf(total_qty));
holder.etQty.setText(String.valueOf(total_qty));
holder.total.setText(" = "
+ (Float.parseFloat(orderItems.get(position)
.getItemPrice()) * Float
.parseFloat(holder.etQty.getText().toString())));
}
});
holder.btnMinus = (Button) convertView
.findViewById(R.id.btnDecreaseQty);
holder.btnMinus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Float total_qty = (Float.parseFloat(holder.etQty.getText()
.toString()) - 1);
if (total_qty != 0) {
Item item = (Item) holder.etQty.getTag();
item.setNoItems(String.valueOf(total_qty));
holder.etQty.setText(String.valueOf(total_qty));
holder.total.setText(" = "
+ (Float.parseFloat(orderItems.get(position)
.getItemPrice()) * Float
.parseFloat(holder.etQty.getText()
.toString())));
}
}
});
holder.btnDelete = (Button) convertView
.findViewById(R.id.btnDeleteItem);
holder.btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
helper.deleteItem(orderItems.get(position).getItemID());
orderItems.remove(position);
notifyDataSetChanged();
}
});
holder.total = (TextView) convertView.findViewById(R.id.tvTotal);
holder.etQty.setTag(orderItems.get(position));
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.etQty.setTag(orderItems.get(position));
}
holder.name.setText(orderItems.get(position).getItemName());
holder.desc.setText(orderItems.get(position).getItemDescription());
holder.price.setText(orderItems.get(position).getItemPrice() + " x ");
holder.etQty.setText(orderItems.get(position).getNItems());
holder.total
.setText(" = "
+ (Float.parseFloat(orderItems.get(position)
.getItemPrice()) * Float
.parseFloat(holder.etQty.getText().toString())));
return convertView;
}
}
my problem is how to call the data from edit text to add it with the each item
for example the item name is :"Cheese Pizza" i want it "2 Cheese Pizza"
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
item_ids = new StringBuilder();
for (int i = 0; i < orderItems.size(); i++) {
item_ids.append(orderItems.get(i).getItemID()).append(",");
}
if (item_ids.length() == 0)
return false;
else
item_ids.deleteCharAt(item_ids.length() - 1);
Log.d("OrderPreview", item_ids.toString());
item_names = new StringBuilder();
for (int i = 0; i < orderItems.size(); i++) {
item_names.append(orderItems.get(i).getItemName()).append(",");
}
if (item_names.length() == 0)
return false;
else
item_names.deleteCharAt(item_names.length() - 1);
Log.d("OrderPreview", item_names.toString());
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(Utils.WS_ADD_ORDER);
List<NameValuePair> mParams = new ArrayList<NameValuePair>();
mParams.add(new BasicNameValuePair("name", etName.getText()
.toString()));
mParams.add(new BasicNameValuePair("phone", etPhone.getText()
.toString()));
mParams.add(new BasicNameValuePair("table", etTable.getText()
.toString()));
mParams.add(new BasicNameValuePair("order_status", "Processing"));
mParams.add(new BasicNameValuePair("id", item_ids.toString()));
mParams.add(new BasicNameValuePair("items", item_names.toString()));

Write a method in your adapter to add new items in existing list of items.
and call that method in your async task when you are getting new dataset from your services/APIs.. Do not forget to put notifyDataSetChanged() in that method inside adapter.

Related

Custom listview in Textview Value change by Scrolling

This Is my Adapter problem was scroll listview to change textview value by every position how to solve it ? plus click event to increment one and minus event to decrment and set value in textview (Plus click to quantity + 1 , minus click to quantity - 1).
public class CustomListViewDrycleaning extends BaseAdapter {
ArrayList<ProductModel> myList = new ArrayList<ProductModel>();
LayoutInflater inflater;
Context context;
int loader = R.drawable.loader;
int minteger = 0;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
String rem, b;
private DisplayImageOptions options;
ProductModel currentListData;
String cid, qcount;
public CustomListViewDrycleaning(Context context, ArrayList<ProductModel> list) {
this.myList = list;
this.context = context;
inflater = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_launcher) .showImageForEmptyUri(R.drawable.ic_launcher).showImageOnFail(R.drawable.ic_launcher) .cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).build();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return myList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return myList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final MyViewHolder mViewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.customproductlistdrycleaning, parent, false);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
currentListData = myList.get(position);
mViewHolder.btndropdown.setTag(currentListData.getCategoryId());
mViewHolder.name.setText(currentListData.getName());
mViewHolder.prize.setText("$" + currentListData.getCharge());
mViewHolder.name.setTag(currentListData.getCategoryId());
mViewHolder.plus.setTag(currentListData.getCategoryId());
mViewHolder.minus.setTag(currentListData.getCategoryId());
String img_path = currentListData.getImage();
ImageLoader.getInstance().displayImage(img_path, mViewHolder.imgbucket, options, animateFirstListener);
String servicecheck1 = currentListData.getServiceId1();
String servicecheck2 = currentListData.getServiceId2();
String servicecheck3 = currentListData.getServiceId3();
if (servicecheck1 == null) {
mViewHolder.btndropdown.setVisibility(View.GONE);
} else {
mViewHolder.btndropdown.setVisibility(View.VISIBLE);
}
mViewHolder.btndropdown.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mViewHolder.lnrbelowdry.setVisibility(View.VISIBLE);
mViewHolder.btndropdown.setVisibility(View.GONE);
mViewHolder.btndropdown1.setVisibility(View.VISIBLE);
}
});
mViewHolder.btndropdown1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mViewHolder.lnrbelowdry.setVisibility(View.GONE);
mViewHolder.btndropdown.setVisibility(View.VISIBLE);
mViewHolder.btndropdown1.setVisibility(View.GONE);
}
});
if (servicecheck1 == null) {
mViewHolder.btndropdown.setVisibility(View.GONE);
mViewHolder.lnrproduct1.setVisibility(View.GONE);
} else {
mViewHolder.btndropdown.setVisibility(View.VISIBLE);
mViewHolder.lnrproduct1.setVisibility(View.VISIBLE);
mViewHolder.checkBox1.setText(currentListData.getServiceName1());
mViewHolder.txtproductprize1.setText("$" + currentListData.getServiceCharge1());
}
if (servicecheck2 == null) {
mViewHolder.lnrproduct2.setVisibility(View.GONE);
} else {
mViewHolder.lnrproduct2.setVisibility(View.VISIBLE);
mViewHolder.checkBox2.setText(currentListData.getServiceName2());
mViewHolder.txtproductprize2.setText("$" + currentListData.getServiceCharge2());
}
if (servicecheck3 == null) {
mViewHolder.lnrproduct3.setVisibility(View.GONE);
} else {
mViewHolder.lnrproduct3.setVisibility(View.VISIBLE);
mViewHolder.checkBox3.setText(currentListData.getServiceName3());
mViewHolder.txtproductprize3.setText("$" + currentListData.getServiceCharge3());
}
qcount = currentListData.getQuantity();
mViewHolder.plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Utils.COUNTCARTALIST.add(mViewHolder.name.getTag() + "");
int quantityyp = 0;
for (int m = 0; m < Utils.qtylist.size(); m++) {
String ii = mViewHolder.plus.getTag() + "";
Log.e("", "#ii" + ii);
if (mViewHolder.plus.getTag().equals(Utils.qtylist.get(m).get("categoryId"))) {
Toast.makeText(context, "Match", Toast.LENGTH_SHORT).show();
rem = Utils.qtylist.get(m).get("categoryId");
b = Utils.qtylist.get(m).get("quantity");
quantityyp = Integer.parseInt(b) + 1;
String c = Integer.toString(quantityyp);
mViewHolder.strcount.setText(c);
Utils.qtylist.remove(m);
HashMap<String, String> hashmaplus = new HashMap<String, String>();
hashmaplus.put("categoryId", rem);
hashmaplus.put("quantity", c);
Utils.qtylist.add(hashmaplus);
Log.e("", "#Utils.qtylistadd" + Utils.qtylist);
break;
}
}
}
});
mViewHolder.minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Utils.COUNTCARTALIST.remove(mViewHolder.name.getTag() + "");
int quantityym = 0;
for (int m = 0; m < Utils.qtylist.size(); m++) {
String ii = mViewHolder.minus.getTag() + "";
Log.e("", "#iiminus" + ii);
if (mViewHolder.minus.getTag().equals(Utils.qtylist.get(m).get("categoryId"))) {
rem = Utils.qtylist.get(m).get("categoryId");
b = Utils.qtylist.get(m).get("quantity");
Log.e("", "#QQQ" + b);
Log.e("", "#rem" + rem);
if (b.equals("0")) {
} else {
quantityym = Integer.parseInt(b) - 1;
String c = Integer.toString(quantityym);
mViewHolder.strcount.setText(c);
Utils.qtylist.remove(m);
HashMap<String, String> hashmapminus = new HashMap<String, String>();
hashmapminus.put("categoryId", rem);
hashmapminus.put("quantity", c);
Utils.qtylist.add(hashmapminus);
break;
}
}
}
}
});
return convertView;
}
private class MyViewHolder {
TextView name, prize, strcount, txtproductprize1, txtproductprize2, txtproductprize3;
Button cart, plus, minus, btndropdown, btndropdown1;
ImageView imgbucket;
LinearLayout lnrbelowdry, lnrproduct1, lnrproduct2, lnrproduct3;
CheckBox checkBox1, checkBox2, checkBox3;
public MyViewHolder(View item) {
name = (TextView) item.findViewById(R.id.txtproductname);
prize = (TextView) item.findViewById(R.id.txtprize);
strcount = (TextView) item.findViewById(R.id.txtcount);
imgbucket = (ImageView) item.findViewById(R.id.imgbucket);
plus = (Button) item.findViewById(R.id.btnplus);
minus = (Button) item.findViewById(R.id.btnminus);
btndropdown = (Button) item.findViewById(R.id.btndropdown);
btndropdown1 = (Button) item.findViewById(R.id.btndropdown1);
lnrbelowdry = (LinearLayout) item.findViewById(R.id.lnrbelowdry);
lnrproduct1 = (LinearLayout) item.findViewById(R.id.lnrproduct1);
lnrproduct2 = (LinearLayout) item.findViewById(R.id.lnrproduct2);
lnrproduct3 = (LinearLayout) item.findViewById(R.id.lnrproduct3);
checkBox1 = (CheckBox) item.findViewById(R.id.checkBox1);
checkBox2 = (CheckBox) item.findViewById(R.id.checkBox2);
checkBox3 = (CheckBox) item.findViewById(R.id.checkBox3);
txtproductprize1 = (TextView) item.findViewById(R.id.txtproductprize1);
txtproductprize2 = (TextView) item.findViewById(R.id.txtproductprize2);
txtproductprize3 = (TextView) item.findViewById(R.id.txtproductprize3);
}
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
You are returning a same ID for each row. try this:
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

Can not set value to list view using custom adapter

When I am trying to set value to the list view using custom adapter it shows only the last entered value in the hash map. hash map is static.I dont know why I am not getting all the values in the hashmap for that keys I am used in hashmap.
here my code
public class Nextclass extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nextclass);
list = (ListView)findViewById(R.id.list1);
SelectItems();
ViewItems();
}
private List<Map<String, String>> SelectItems() {
// TODO Auto-generated method stub
try {
datas = new ArrayList<Map<String, String>>();
DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("select distinct code ,desc ,name "
+ " from item", null);
while (c.moveToNext()){
String cod = c.getString(c.getColumnIndex("code"));
datanums.put("code", cod);
String desc1 = c.getString(c.getColumnIndex("desc"));
datanums.put("desc", desc1);
String name = c.getString(c.getColumnIndex("name"));
datanums.put("name", name);
datas.add(datanums);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
return datas;
}
private void ViewItems() {
// TODO Auto-generated method stub
arrTemp = new String[datas.size()];
MyListAdapter myListAdapter = new MyListAdapter();
list.setAdapter(myListAdapter);
Log.v("list itemm",datas.toString());
}
public class MyListAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
if(datas != null && datas.size() != 0){
return datas.size();
}
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return datas.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = Orders.this.getLayoutInflater();
convertView = inflater.inflate(R.layout.order_simple_row, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.name);
holder.textView2 = (TextView) convertView.findViewById(R.id.code);
holder.textview3 = (TextView) convertView.findViewById(R.id.desc);
holder.editText1 = (EditText) convertView.findViewById(R.id.cases);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ref = position;
holder.textView1.setText(datanums.get("name"));
holder.textview3.setText(datanums.get("code"));
holder.textView2.setText(datanums.get("desc"));
holder.editText1.setText(arrTemp[position]);
holder.editText1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#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
arrTemp[holder.ref] = arg0.toString();
}
});
return convertView;
}
private class ViewHolder {
public Object list;
TextView textView1,textView2,textview3;
EditText editText1,editText2;
int ref;
}
return convertView;
}
private class ViewHolder {
public Object list;
TextView textView1,textView2,textview3;
EditText editText1;
int ref;
}
please help.I used alternate methods,but not worked.thanks in advance
holder.textView1.setText(datas.get(position).get("name"));
holder.textview3.setText(datas.get(position).get("code"));
holder.textView2.setText(datas.get(position).get("desc"));
you are adding hash map in the array list but in the adapter you are trying to get data from the hash map, instead of that you need to take value from arraylist which will return hashmap object and from that object you need to get value for your keys.
hope this will help.

Custom BaseAdapter wont add new Data - Android

I have a custom baseadapter that creates comment boxes. Everything works great on it until I want to add data. When I try to add the data it deletes the previous data and adds the new data. How do I make it so it keeps all the data? Is my Add method incorrect? Here is my baseadapter,
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(String[] comments, String[] usernames, String[] numbers, DashboardActivity context)
{
super();
ctx_invitation = context;
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
#Override
public int getCount() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
public int getCount1() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
public Object getItem1(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
public long getItemId1(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView1(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
}
Setting the adapter:
final CreateCommentLists mycmlist = new CreateCommentLists(comments, usernames, numbers, DashboardActivity.this);
lstComments = (ListView)findViewById(android.R.id.list);
lstComments.setAdapter(mycmlist);
This is what how I call the add method,
mycmlist.add(comments,usernames,numbers);
mycmlist.notifyDataSetChanged();
In your add method you're setting the arrays to new values listComments = comments; That's replacing your old data with the new data.
You could use System.arrayCopy() to resize your listArrays to the new size and append the new items. A much less tedious approach, however, would be to store your arrays as List<String>, allowing you to add more items without worrying about resizing lists.
The result would look something like this...
public class CommentsAdapter extends BaseAdapter
{
private LayoutInflater inflater;
private List<String> comments;
private List<String> numbers;
private List<String> usernames;
public CommentsAdapter(Context context)
{
inflater = LayoutInflater.from(context);
comments = new ArrayList<String>();
numbers = new ArrayList<String>();
usernames = new ArrayList<String>();
}
public void add(String[] comments, String[] numbers, String[] usernames)
{
this.comments.addAll(Arrays.asList(comments));
this.numbers.addAll(Arrays.asList(numbers));
this.usernames.addAll(Arrays.asList(usernames));
notifyDataSetChanged();
}
#Override
public int getCount()
{
if (comments == null)
return 0;
return comments.size();
}
#Override
public String getItem(int position)
{
return comments.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = inflater.inflate(R.layout.list_item, parent, false);
convertView.setTag(new ViewHolder(convertView));
}
ViewHolder holder = (ViewHolder) convertView.getTag();
holder.commentView.setText(comments.get(position));
//Other view bind logic here...
return convertView;
}
private static class ViewHolder
{
public TextView commentView;
public TextView numbersView;
public TextView usernamesView;
public Button usernameButton;
public Button numberButton;
public ViewHolder(View v)
{
commentView = (TextView) v.findViewById(R.id.listComment);
numbersView = (TextView) v.findViewById(R.id.listNumber);
usernamesView = (TextView) v.findViewById(R.id.listPostedBy);
usernameButton = (Button) v.findViewById(R.id.listUsernameButton);
numberButton = (Button) v.findViewById(R.id.listNumberButton);
}
}
}
I also highly recommend reading this page on the Android Developer's site: http://developer.android.com/training/improving-layouts/smooth-scrolling.html
Your current adapter implementation is very inefficient, and that page should help you iron out some kinks.
You probably need to add the String[] array to the existing one, instead of replacing it.
Add this function which joins two arrays (Sadly there is no already-implemented method for Java):
String[] concat(String[] A, String[] B) {
String[] C= new String[A.length + B.length];
System.arraycopy(A, 0, C, 0, A.length);
System.arraycopy(B, 0, C, A.length, B.length);
return C;
}
Credits: Sun Forum
And then change the add method to this:
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = concat(listComments, comments);
listUsernames = concat(listUsernames, usernames);
listNumbers = concat(listNumbers, numbers);
}
And you had a typo in your code. In the add method, the listUsernames and listNumbers should be swapped I think.. I fixed it for you.

Android List with check box

I have list with a check box in it and when i tick the check box by scrolling the list i get the values into an array.
But now the problem is i have a search box to search and tick.but when i search i get the element which is last ticked into array.
here is my code.
public class Person extends ListActivity {
private TreeMap<String, String> map = new TreeMap<String, String>();
String SEARCH_STRING = "";
private String METHOD_NAME;
private String SERVICENAME;
ArrayList<String[]> DISPLAY = new ArrayList<String[]>();
ArrayList<String[]> SEARCH = new ArrayList<String[]>();
ArrayList<Boolean> ok = new ArrayList<Boolean>();
SoapIntractions intractions;
public static ArrayList<String[]> dataList=new ArrayList<String[]>();
boolean FLAG;
EditText search;
Button search_btn, back_btn;
LinearLayout tab1, tab2;
public Context c;
static class Viewholder {
TextView name, number;
CheckBox check;
}
public class EfficientAdapter extends BaseAdapter {
LayoutInflater inflater;
Context c;
public EfficientAdapter(Context addNote, int itemadd, Object object,
int[] to) {
// TODO Auto-generated constructor stub
inflater = LayoutInflater.from(addNote);
c = addNote;
}
public int getCount() {
// TODO Auto-generated method stub
return SEARCH.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Viewholder holder;
final int var = position;
if (convertView == null) {
convertView = inflater.inflate(R.layout.person, null);
holder = new Viewholder();
holder.name = (TextView) convertView
.findViewById(R.id.tv_name_prsnLI);
holder.number = (TextView) convertView
.findViewById(R.id.tv_nmbr_prsnLI);
holder.check = (CheckBox) convertView.findViewById(R.id.check);
convertView.setTag(holder);
} else {
holder = (Viewholder) convertView.getTag();
}
CheckBox box=new CheckBox(c);
String[] argg = SEARCH.get(var);
holder.name.setText(argg[0]);
holder.number.setText(argg[1]);
if (ok.get(position)){
holder.check.setChecked(true);
}
else{
holder.check.setChecked(false);
}
holder.check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (ok.get(var)) {
ok.set(var, false);
} else {
ok.set(var, true);
}
}
});
return convertView;
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.person_list);
StateListDrawable bkBtn = new StateListDrawable(), srchBtn = new StateListDrawable();
bkBtn.addState(new int[] { android.R.attr.state_pressed },
getResources().getDrawable(R.drawable.back_click));
bkBtn.addState(new int[] {}, getResources()
.getDrawable(R.drawable.back));
srchBtn.addState(new int[] { android.R.attr.state_pressed },
getResources().getDrawable(R.drawable.srch_click));
srchBtn.addState(new int[] {},
getResources().getDrawable(R.drawable.srch));
search = (EditText) findViewById(R.id.et_search_prsnL);
search_btn = (Button) findViewById(R.id.btn_search_prsnL);
search_btn.setBackgroundDrawable(srchBtn);
back_btn = (Button) findViewById(R.id.btn_back_prsnL);
back_btn.setBackgroundDrawable(bkBtn);
tab1 = (LinearLayout) findViewById(R.id.lyt_tab1_prsnL);
tab2 = (LinearLayout) findViewById(R.id.lyt_tab2_prsnL);
tab1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FLAG = false;
tab1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head_click));
tab2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head));
}
});
tab2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
FLAG = true;
tab2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head_click));
tab1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head));
}
});
search_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SEARCH_STRING = search.getText().toString();
SEARCH.clear();
SearchPageTask srch_task = new SearchPageTask();
srch_task.execute(new String[] { null });
Log.d("SEARCH", "Searchable");
}
});
back_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int len=ok.size();
for(int i=0;i<len;i++){
if(ok.get(i)){
dataList.add(new String[]{SEARCH.get(i)[0],SEARCH.get(i)[1],SEARCH.get(i)[2],SEARCH.get(i)[3] });
}
}
Intent in=new Intent(getApplicationContext(),Multiple_view.class);
in.putExtra("ARRAY", dataList);
setResult(RESULT_OK,in);
finish();
for (int i = 0; i < dataList.size(); i++) {
Log.d("ARRAY1", ""+dataList.get(i)[0]);
Log.d("ARRAY1", ""+dataList.get(i)[1]);
Log.d("ARRAY1", ""+dataList.get(i)[2]);
Log.d("ARRAY1", ""+dataList.get(i)[3]);
}
}
});
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
FLAG = false;
tab1.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head_click));
tab2.setBackgroundDrawable(getResources().getDrawable(
R.drawable.list_head));
METHOD_NAME = "ZaplxTmrDisplayPernr";
SERVICENAME = "ZAPLX_WEB_TMR_DISPLAY_PERNR/ZaplxTmrDisplayPernrRequest";
map = new TreeMap<String, String>();
map.put("IDate", "2012-12-04");
intractions = new SoapIntractions(METHOD_NAME, SERVICENAME, map,
Person.this);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { null });
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Log.d("POSITION", "" + position);
// CheckBox cb = (CheckBox)
// l.getChildAt(position).findViewById(R.id.check);
// if (cb.isChecked()) {
// cb.setChecked(false);
//
// }
// else
// {
// cb.setChecked(true);
// }
// Intent in1=new Intent();
// String[] argg1 = SEARCH.get(position);
//
// in1.putExtra("number", SEARCH.get(position)[0]);
// in1.putExtra("name", SEARCH.get(position)[1]);
// in1.putExtra("area", SEARCH.get(position)[2]);
// in1.putExtra("group", SEARCH.get(position)[3]);
// setResult(RESULT_OK,in1);
// finish();
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
String[][] data;
int value = 0;
ProgressBar pb;
public DownloadWebPageTask() {
// TODO Auto-generated constructor stub
// flag = string;
value = 0;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
data = intractions.GetSoapData1();
String[][] subtypeData = data;
int n = subtypeData[0].length;
value = n;
for (int i = 0; i < value; i++) {
String Pernr = subtypeData[0][i];
String Ename = subtypeData[1][i];
String Earea = subtypeData[3][i];
String Egroup = subtypeData[5][i];
ok.add(false);
DISPLAY.add(new String[] { Pernr, Ename, Earea, Egroup });
}
for (int i = 0; i < DISPLAY.size(); i++)
SEARCH.add(DISPLAY.get(i));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
// pb = (ProgressBar) findViewById(R.id.pb);
// pb.setVisibility(View.VISIBLE);
search_btn.setClickable(false);
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// pb = (ProgressBar) findViewById(R.id.pb);
// pb.setVisibility(View.INVISIBLE);
setListAdapter(new EfficientAdapter(Person.this, R.layout.person,
null, null));
search_btn.setClickable(true);
Log.d("POST_TIME", "Inside post");
super.onPostExecute(result);
}
}
private class SearchPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.d("SEARCH", "List Size" + DISPLAY.size());
Log.d("SEARCH", "List Size" + SEARCH.size());
int n = DISPLAY.size();
if (!FLAG) {
for (int i = 0; i < n; i++) {
if (DISPLAY.get(i)[1].toLowerCase().startsWith(
SEARCH_STRING.toLowerCase())) {
SEARCH.add(DISPLAY.get(i));
Log.d("SEARCH_ATSK", "result size " + SEARCH.size());
}
Log.d("SEARCH_ATSK", "" + i + " " + n);
}
} else {
for (int i = 0; i < n; i++) {
if (DISPLAY.get(i)[0].toLowerCase().endsWith(
SEARCH_STRING.toLowerCase())) {
SEARCH.add(DISPLAY.get(i));
Log.d("SEARCH_ATSK", "result size " + SEARCH.size());
}
Log.d("SEARCH_ATSK", "" + i + " " + n);
}
}
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
setListAdapter(new EfficientAdapter(Person.this, R.layout.person,
null, null));
super.onPostExecute(result);
}
}
}

how to iterate through each checkboxes in each row of a listview in android?

I have an application with three textviews and one checkbox in each row of a listview.what I want that on a click of a button I will be able to get the state of each checkbox and the row corresponding to (isChecked) checkboxes get deleted.one more thing my checkboxes are hardcoded in an xml file.I have searched a lot but couldn't find anything specific.thanks in advance.HERE IS MY CODE...
public class recentcalllistultimate extends ListActivity implements OnClickListener {
CheckBox cb;
Button edit,done;
ImageButton contacts;
ListView lv;
ListView lvultimate;
listviewadapterultimate lvar;
int[] uniqueid;
String[] names;
String[] types;
;
RelativeLayout rl;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
LayoutParams params=newRelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
LinearLayout mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
LayoutInflater layoutInflater = getLayoutInflater();
mainLayout.addView(layoutInflater.inflate(R.layout.listviewonly, null));
mainLayout.addView(layoutInflater.inflate(R.layout.allbuttons, null));
this.addContentView(mainLayout, params);
cb = (CheckBox) findViewById(R.id.checkboxdelete);
getContacts();
lv = (ListView) findViewById(android.R.id.list);
lvar = new listviewadapterultimate(this, names, types,uniqueid);
lv.setAdapter(lvar);
contacts = (ImageButton) findViewById(R.id.button_keypad);
contacts.setOnClickListener(this);
edit = (Button) findViewById(R.id.editbutton);
done=(Button)findViewById(R.id.donebutton);
done.setOnClickListener(new View.OnClickListener() {
------>>> public void onClick(View v) {
// TODO Auto-generated method stub
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, booleanisChecked) {
// TODO Auto-generated method stub
//WHAT TO DO HERE....
}
}
});
}
------>>> });
edit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
AddDialog ada=new AddDialog(recentcalllistultimate.this);
ada.show();
}
});
}// on create
public void getContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(android.provider.CallLog.Calls.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
int i = 0;
int foo = 0;
names = new String[cur.getCount()];
types = new String[cur.getCount()];
duration = new long[cur.getCount()];
uniqueid = new int[cur.getCount()];
int n = cur.getColumnIndex(CallLog.Calls._ID);
int k = cur.getColumnIndex(CallLog.Calls.CACHED_NAME);
int y = cur.getColumnIndex(CallLog.Calls.NUMBER);
int z = cur.getColumnIndex(CallLog.Calls.CACHED_NUMBER_TYPE);
while (cur.moveToNext()) {
uniqueid[foo] = cur.getInt(n);
String str = cur.getString(k);
if (str == null) {
names[foo] = cur.getString(y);
}// if
else {
names[foo] = str;
}
int temp = cur.getInt(z);
switch (temp) {
case 0:
types[foo] = "unknown";
break;
case 1:
types[foo] = "home";
break;
case 2:
types[foo] = "mobile";
break;
case 3:
types[foo] = "work";
break;
}// switch
long doo = cur.getInt(d);
duration[foo] = doo;
foo++;
} // while
}// if
}//getcontacts
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==contacts){
Intent intent = new Intent();
intent.setClassName("com.a.Activities",
"com.a.Activities.DialPad");
startActivity(intent);
finish();
}
}
}// class
.................................
public class listviewadapterultimate extends BaseAdapter {
viewHolder holder;
Activity context;
String[] names;
String[] types;
String[] duration;
int[] uniqueid;
public listviewadapterultimate(Activity context, String[] names,
String[] types, int[] uniqueid2 ) {
this.context = context;
this.names = names;
this.types = types;
uniqueid=uniqueid2;
}
public int getCount() {
// TODO Auto-generated method stub
return names.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public class viewHolder {
TextView top;
TextView bottom;
TextView down;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
holder = new viewHolder();
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.recenttextviewonlyultimate, null);
holder.top = (TextView) convertView.findViewById(R.id.toptext_u);
holder.bottom = (TextView) convertView
.findViewById(R.id.bottomtext_u);
holder.down = (TextView) convertView.findViewById(R.id.recentuniqueid_u);
convertView.setTag(holder);
} else {
holder = (viewHolder) convertView.getTag();
//holder.cb.setVisibility(View.VISIBLE);
}
holder.top.setText(names[position]);
holder.bottom.setText(types[position]);
holder.down.setText("" + uniqueid[position]);
return convertView;
}
}
................
Try this:
Inside your getView(...) method...
final CheckBox lChk = ((CheckBox) pConvertView.findViewById(R.id.myChkBoxID));
private List<lisInfo> m_lisInfo = new ArrayList<lisInfo>();
lChk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Populate the listInfo with check box status
m_lisInfo.get(lPosition).setChkBoxStatus((isChecked));
}
});
public class lisInfo{
private boolean chkBoxStatus;
public boolean isChkBoxStatus() {
return chkBoxStatus;
}
public void setChkBoxStatus(boolean chkBoxStatus) {
this.chkBoxStatus = chkBoxStatus;
}
}
Now iterate the listInfo wherever required to get the check boxes statuses in the list view
maintain an array of boolean inside adapter . set listener on ckeckbox in getview which will swipe values of array on check/uncheck .
now make this array accesible in activity where on button
click()
{
for(int i=0;i<array.size;i++)
{
if(array[i])
adapter.deelet(item i);
//modify syntax
}
}

Categories

Resources