Looping through ListView twice - android

I have an activity with a custom ListView. I have two TextViews in each row, one of them contains static text and the other contains numbers which are randomly changed on a Button press. I need to save the data of both TextViews in two seperate ArrayLists (if the value of the number TextView is not 0). The values are being stored inside the ArrayLists as I wish, however the records are being inserted twice; such that when I loop through the ArrayList and show them in a Toast I get twice the value of the rows entered.
Below are my code snippets:
On Button click adding value of Number TextView
holder.add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int temp = numPickerValues.get(position);
temp += 1;
numPickerValues.set(position, temp);
notifyDataSetChanged();
}
});
holder.num.setText(String.valueOf(numPickerValues.get(position)));
Adding values of non-0 TextViews to ArrayList
if(!holder.num.getText().equals("0"))
{
materialNames.add(holder.txt.getText().toString());
materialAmounts.add(holder.num.getText().toString());
}
This is the fun part.
I debugged the application to check where the problem lies and I found out it is looping inside the ListView twice and thus storing the values twice inside the ArrayLists, however I do not have the values duplicated in my ListView. The duplicated value of one TextView is being shown after another, so it is not exactly looping twice, otherwise the values would be separated by others.
Any idea of what is going on?
Displaying values
public String getTest()
{
test= "";
for(String i : materialNames)
{
test = test + " " + i;
}
return test;
}
Then I call the above method from another activity on Button Click
btnConfirm.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast tt = Toast.makeText(getApplicationContext(), adapter.getTest(), Toast.LENGTH_LONG);
tt.show();
}
});
Custom Adapter class
public class MaterialListViewAdapter extends BaseAdapter
{
ViewHolder holder;
int counter = 0;
String test = null;
TextView txtNum;
private ArrayList<MaterialClass> data;
private ArrayList<Integer> numPickerValues;
private ArrayList<String> materialNames;
private ArrayList<String> materialAmounts;
public static LayoutInflater inflater = null;
public static Dialog dialog;
String materialName;
public MaterialListViewAdapter(Context applicationContext,
int materialdialogcontent, ArrayList<MaterialClass> materials)
{
this.data = materials;
this.numPickerValues = new ArrayList<Integer>();
this.materialNames = new ArrayList<String>();
this.materialAmounts = new ArrayList<String>();
int size = Material.materialList.size();
for(int i=0; i < size; i++)
{
this.numPickerValues.add(0);
}
inflater = (LayoutInflater)applicationContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount()
{
return data.size();
}
#Override
public Object getItem(int position)
{
return position;
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
if(convertView == null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.materialdialogcontent, null);
holder.txt = (TextView)convertView.findViewById(R.id.txtMaterialName);
holder.add = (Button)convertView.findViewById(R.id.btnAdd);
holder.sub = (Button)convertView.findViewById(R.id.btnSub);
holder.num = (TextView)convertView.findViewById(R.id.txtNum);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
holder.txt.setText(data.get(position).getName());
holder.add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int temp = numPickerValues.get(position);
temp += 1;
numPickerValues.set(position, temp);
notifyDataSetChanged();
}
});
holder.sub.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
int temp = numPickerValues.get(position);
temp -= 1;
numPickerValues.set(position, temp);
notifyDataSetChanged();
}
});
holder.num.setText(String.valueOf(numPickerValues.get(position)));
if(!holder.num.getText().equals("0"))
{
materialNames.add(holder.txt.getText().toString());
materialAmounts.add(holder.num.getText().toString());
}
return convertView;
}
public String getTest()
{
test= "";
for(String i : materialNames)
{
test = test + " " + i;
}
return test;
}
private static class ViewHolder
{
TextView txt;
Button add;
Button sub;
TextView num;
}
}

if(!holder.num.getText().equals("0"))
{
materialNames.add(holder.txt.getText().toString());
materialAmounts.add(holder.num.getText().toString());
}
Above code in getView may be run many times. So, you can use HashMap instead of your materialNames and materialAmounts to avoid duplication.

Related

How to modify only one row at a time while using Customized ListView

I have used Customized ListView And not ExtendedListView. i have taken relative layout in order to show it as sub_list. By default i have set the visibilty of this sub_list relative layout as GONE. And on the click of any listItem that relative layout(by default set as gone) will appear on the screen respectively. But When I click on any of the rows the sub_list appear for each row simultaneously. What i want is that it should be shown only for one row at a time. I have already checked this similar [question]: How to modify only one row at a time in Listview? and modified my code but still i am unable to achieve my goal.
Here is my pieace of code:
public class CustomAdapter extends BaseAdapter {
Activity context;
ArrayList<String> s_date,c_number,d_ration,s_time,download_path,a_number,a_name,dt_number;
int flag=0,temp=1,position;
String mUrl;
int posview;
private int selectedIndex;
CustomAdapter(Activity context, ArrayList<String> start_date, ArrayList<String> caller_number, ArrayList<String> duration,ArrayList<String> start_time, ArrayList<String> download_path, ArrayList<String> agent_number, ArrayList<String> agent_name,ArrayList<String> dt_num)
{
this.context=context;
this.s_date=start_date;
this.c_number=caller_number;
this.d_ration=duration;
this.s_time=start_time;
this.download_path=download_path;
this.a_number=agent_number;
this.a_name=agent_name;
this.dt_number=dt_num;
selectedIndex = -1;
}
public void setSelectedIndex(int ind)
{
selectedIndex = ind;
notifyDataSetChanged();
}
#Override
public int getCount() {
return s_date.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int pos, final View v, ViewGroup g)
{
//LayoutInflater l=context.getLayoutInflater();
//View rowView=l.inflate(R.layout.log_layout,null,true);
posview=pos;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View row = inflater.inflate(R.layout.list_item, g, false);
TextView start_date = (TextView) row.findViewById(R.id.start_date);
start_date.setText(s_date.get(pos));
TextView caller_number = (TextView) row.findViewById(R.id.caller_number);
caller_number.setText(c_number.get(pos));
TextView duration = (TextView) row.findViewById(R.id.duration);
duration.setText(d_ration.get(pos));
TextView start_time = (TextView) row.findViewById(R.id.start_time);
start_time.setText(s_time.get(pos));
TextView agent_name = (TextView) row.findViewById(R.id.agent_name);
agent_name.setText(a_name.get(pos));
TextView agent_number = (TextView) row.findViewById(R.id.agent_number);
agent_number.setText(a_number.get(pos));
TextView dt_numb=(TextView)row.findViewById(R.id.dt_number);
dt_numb.setText("MHL No. -"+dt_number.get(pos));
RelativeLayout r = (RelativeLayout)row.findViewById(R.id.sub_layout);
r.setVisibility(position == posview ? View.VISIBLE : View.GONE);
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
posview=pos;
notifyDataSetChanged();
}
});
return row;
}
}
Previously my code was:
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setSelectedIndex(view.getId());
RelativeLayout sub_list = (RelativeLayout) row.findViewById(R.id.sub_layout);
sub_list.setVisibility(View.VISIBLE);
//notifyDataSetChanged();
}
});
I am getting all the data dynamically. This is how i'm using the adapter in MainActivity:
CustomAdapter a=new CustomAdapter(MainScreen.this,start_date,caller_number,duration,start_time,download_path,agent_number,agent_name,dt_number);
data_list.setAdapter(a);
In this start_date caller_number etc are arraylist.This is how i'm parsing data in MainActivity.
JSONObject responseObject = new JSONObject(response);
JSONObject callLog = responseObject.getJSONObject("call_log");
Iterator<String> phoneNumbers = callLog.keys();
while (phoneNumbers.hasNext()) {
String number = phoneNumbers.next();
// Log.v("string number",number);
JSONObject numberLog = callLog.getJSONObject(number);
Iterator<String> callEntries = numberLog.keys();
while (callEntries.hasNext()) {
String entry = callEntries.next();
//Log.v("unique keys are",entry);
JSONObject entryObject = numberLog.getJSONObject(entry);
jsonArray.put(entryObject.getString("start_date"));
jsonArray.put(entryObject.getString("start_time"));
jsonArray.put(entryObject.getString("end_date"));
jsonArray.put(entryObject.getString("end_time"));
jsonArray.put(entryObject.getString("recording_path"));
String startDate = entryObject.getString("start_date");
start_date.add(startDate);
String startTime = entryObject.getString("start_time");
start_time.add(startTime);
String endDate = entryObject.getString("end_date");
String endTime = entryObject.getString("end_time");
String call_sdate = entryObject.getString("call_sdate");
String call_edate = entryObject.getString("call_edate");
String call_type = entryObject.getString("call_type");
String caller = entryObject.getString("caller");
caller_number.add(caller);
String duartion = entryObject.getString("duartion");
String call_duartion = entryObject.getString("call_duartion");
duration.add(call_duartion);
String dtmf = entryObject.getString("dtmf");
String dt_num = entryObject.getString("dt_number");
dt_number.add((dt_num));
String recording_path = entryObject.getString("recording_path");
download_path.add(recording_path);
String agent_mobile = entryObject.getString("agent_mobile");
agent_number.add(agent_mobile);
String a_name = entryObject.getString("agent_name");
agent_name.add(a_name);
Create two variables :
Map<Integer, View> lastExpanded = new HashMap<>();
int lastExpandedPosition =-1;
Create a function in your adapter :
private void expand(int i, View layout){
if(!lastExpanded.containsKey(i)){
layout.setVisibility(View.VISIBLE);
lastExpanded.put(i, layout);
if(lastExpanded.containsKey(lastExpandedPosition)){
expand(lastExpandedPosition, lastExpanded.get(lastExpandedPosition));
}
lastExpanded.remove(lastExpandedPosition);
lastExpandedPosition = i;
lastExpanded.put(lastExpandedPosition, layout);
}else{
layout.setVisibility(View.GONE);
lastExpandedPosition = -1;
lastExpanded.remove(i);
}
}
now,
final RelativeLayout layout = (RelativeLayout) row.findViewById(R.id.b);
layout.setVisibility(View.GONE);
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
expand(i, layout);
}
});
You can acheive this easily with expandable listview and your adapter class should extend BaseExpandableListAdapter
in activity
private int lastExpandedPosition = -1;
expListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
final int groupPosition, long id) {
// TODO Auto-generated method stub
if (parent.isGroupExpanded(groupPosition)) {
expListView
.collapseGroup(lastExpandedPosition);
} else {
expListView.expandGroup(groupPosition);
}
return true;
}
});
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
// TODO Auto-generated method stub
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
expListView
.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
You have to use ArrayList which contents as your data while you click on the item.
public class DataModel{
private String s_date,c_number,d_ration,s_time,download_path,a_number,a_name,dt_number;
private boolean isChildVisible;
..... create it's setter and getter methods.
}
when itemclick is called that time you should update the flag of isChildVisible for that position.
public void setSelectedIndex(int ind)
{
arrayListDataModel.get(ind).setIsChildVisible(true);
notifyDataSetChanged();
}
In your getview method :
public View getView(final int pos, final View v, ViewGroup g)
{
----your initialization code.
RelativeLayout r = (RelativeLayout)row.findViewById(R.id.sub_layout);
r.setVisibility(arrayListDataModel.get(pos).isChildVisible() ? View.VISIBLE : View.GONE);
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setSelectedIndex(pos);
}
});
return row;
}
parse the data with below code :
final ArrayList<DataModel> dataModelList = new ArrayList<>();
while (callEntries.hasNext()) {
DataModel dataModel = new DataModel();
String entry = callEntries.next();
//Log.v("unique keys are",entry);
JSONObject entryObject = numberLog.getJSONObject(entry);
jsonArray.put(entryObject.getString("start_date"));
jsonArray.put(entryObject.getString("start_time"));
jsonArray.put(entryObject.getString("end_date"));
jsonArray.put(entryObject.getString("end_time"));
jsonArray.put(entryObject.getString("recording_path"));
String startDate = entryObject.getString("start_date");
dataModel.setStartDate(startDate);
String startTime = entryObject.getString("start_time");
dataModel.setStartTime(startTime);
...... same as above for others fields
dataModelList.add(dataModel);
}

How to increment TextView value outside ListView when ListView button is clicked in Android

I have a TextView outside ListView and i need to add prices when the plus button (ie,quantity is incremented )in ListView is clicked.In my program i am not able to add prices when new position ListView button is clicked.I need to find the total price to be payed by the customer when plus button is clicked in ListView
public class ListAdapter1 extends BaseAdapter {
public int qty=1;
public ArrayList<Integer> quantity = new ArrayList<Integer>();
private TextView total;
private String[] listViewItems,prices,weight;
TypedArray images;
public static int pValue;
private Context context;
public static boolean t=false;
CustomButtonListener customButtonListener;
public void setTextView(TextView total)
{
this.total = total;
}
public ListAdapter1(Context context, String[] listViewItems, TypedArray images, String[] weight, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices=prices;
this.weight=weight;
}
public void setCustomButtonListener(CustomButtonListener customButtonListner)
{
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return 5;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View row;
final ListViewHolder listViewHolder;
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.product,parent,false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName)
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
row.setTag(listViewHolder);
}
else
{
row=convertView;
listViewHolder= (ListViewHolder) row.getTag();
}
try{
listViewHolder.edTextQuantity.setText(quantity.get(position) );
}catch(Exception e){
e.printStackTrace();
}
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, " " + position, Toast.LENGTH_SHORT).show();
int mValue = Integer.parseInt(listViewHolder.edTextQuantity.getText().toString());
if (mValue <=0) {
System.out.println("not valid");
mValue=0;
listViewHolder.edTextQuantity.setText("" +mValue);
}
else{
pValue=pValue/mValue;
mValue--;
pValue=pValue*mValue;
total.setText(String.valueOf(pValue));
System.out.println("mvalue after reducing-----------"+mValue);
System.out.println("pvalue-----------"+pValue);
listViewHolder.edTextQuantity.setText( "" +mValue );
}
}
});
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, " " + position, Toast.LENGTH_SHORT).show();
int mValue = Integer.parseInt(listViewHolder.edTextQuantity.getText().toString());
pValue=Integer.parseInt(listViewHolder.tvPrices.getText().toString());
mValue++;
listViewHolder.edTextQuantity.setText("" + mValue);
System.out.println("mValue after increment---" + mValue);
pValue=pValue*mValue;
System.out.println("pvalue-----------"+pValue);
total.setText(String.valueOf(pValue));
}
});
return row;
}
I need to get total price when any of the ListView button is clicked.
First you need to store value in HashMap<> when user click the plus and minus button.
Then sum the all values in HashMap.
For Example
try{
int sum = 0;
for(HashMap<String, String> map : arrayList) {
sum += Integer.parseInt(map.get("mark"));
}
} catch (Exception e) {
//Manage your exception
}
// sum has the value for the marks total.
System.out.println("Total Marks: "+sum);
Refere my previous answer Here
For that you need to create interface which notify in activity where you want that count.
put snippet in adapter to initialize interface and setter.
public interface IEvent {
void onItemChange(int count);
}
private IEvent iEvent;
//setter method for interface
public void setQuanityEvent(IEvent ievent) {
this.lastPageHandler = handler;
}
put this code in btnMinus.setOnClickListener
//if ievent interface variable register via set
if (ievent != null) {
//pValue is quality COUNT you want to send outside listview.
ievent.onItemChange(pValue);
}
activity code after creating adapter instance
//ListAdapter1 adapter = new ListAdapter1(your params);
adapter.setQuanityEvent(new ListAdapter1.IEvent() {
#Override
public void onItemChange(int count) {
}
}
});

Listviews with EditText behavior

i've noticed an extrage behavior on my app that has a ListView with three EditTexts,
the problem is that whenever i select one textedit and move away from focus and come back the text i wrote in the first row i selected either desapears or moves to a different row, also when an edittext is focused and i go down in the list it seems that i have selected the edittext in the same position but 10 or 11 rows after the one im actually focusing(the one i can write to).
any knowledge on that case?
also im new to android so i dont know if thats supposed to happen.
this is the List im using.
public class In_List {
private int id;
private String text;
private float a;
private float Qty;
public In_List (int id, String text, float a, float Qty) {
this.id = id;
this.text = text;
this.a = a;
this.Qty= Qty;
}
public String get_text() {
return text;
}
public float get_a() {
return a;
}
public int get_id() {
return id;
}
public float get_Qty() {
return Qty;
}
}
here is the adapter:
public abstract class List_Adapter extends BaseAdapter {
private ArrayList<?> ins;
private int R_layout_IdView;
private Context context;
public Lista_adaptador(Context context, int R_layout_IdView, ArrayList<?> ins) {
super();
this.context = context;
this.ins = ins;
this.R_layout_IdView = R_layout_IdView;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R_layout_IdView, null);
}
onInsert (ins.get(position), view);
return view;
}
#Override
public int getCount() {
return ins.size();
}
#Override
public Object getItem(int position) {
return ins.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public abstract void onInsert (Object insert, View view);
}
and here is the main activity. it has a popup window that i used to fill the value of Qty but i its not included.
public class MainActivity extends Activity {
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listing);
ArrayList<In_List> data = new ArrayList<>();
for(int i=0; i<100; i++){
data.add(new In_List(i, "Item Number :"+i+1, i*2,0));
}
list = (ListView) findViewById(R.id.ListView_listing);
list.setAdapter(new List_Adapter(this, R.layout.entry, data){
#Override
public void onInsert(Object entr, View view) {
if (entr != null) {
TextView id_Text = (TextView) view.findViewById(R.id.textView_id);
if (id_Text != null)
id_Text.setText(((In_List) entr).get_id());
TextView info_Text = (TextView) view.findViewById(R.id.textView_info);
if (info_Text != null)
info_Text.setText(((In_List) entr).get_text());
TextView inside_Text = (TextView) view.findViewById(R.id.textView_inside);
if (inside_Text != null)
inside_Text.setText(((In_List) entr).get_a());
TextView Qty_Text = (TextView) view.findViewById(R.id.textView_qty);
if (Qty_Text != null || Qty_Text.getText().toString().equals(0))
Qty_Text.setText(((In_List) entr).get_Qty());
Qty_Text.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Add_Qty();
}
});
}
}
});
// list.setOnItemClickListener(new OnItemClickListener() {
// #Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// In_List chosen = (In_List) parent.getItemAtPosition(position);
//
// CharSequence text = "Selected: " + chosen.get_textoDebajo();
// Toast toast = Toast.makeText(MainActivity.this, texto, Toast.LENGTH_LONG);
// toast.show();
// }
// });
}
}
now, when i scroll down through the list the Qtys that i have entered either disappear or move to another row.
fixed. i wasn't stablishing Qty_Text value at all. also made a method to save into the adapter array.
EditTexts in generally are very tricky. And using them inside a ListView is almost impossible. The special behaviour of EditTexts for example to always automatically assume focus combinded with the View recycling of the ListViews messes with the ListView and causes a lot of problems. I would suggest you look for another solution. For example placing the EditText inside the HeaderView of the ListView is fine, as the HeaderView is not recycled as you scroll through the ListView.

Automatically check the checkbox that corresponds to the value from the database

I am using a baseadapter for my customize spinner with checkbox that allow the user to choose multiple values. I have an update button in my application, and I need to set the values from the database as true in the checkbox. My problem is I don't know how to do it. For example I have ["A","B","C","D"] values in my spinner, in my database I got B and D. How will i automatically check that values when I open the activity.
Here is my code that populate my customize spinner
private void initializeCustomerSegment() {
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
checkSelectedConsumerSegment = new boolean[consumerSegments.size()];
//initialize all values of list to 'unselected' initially
for (int i = 0; i < checkSelectedConsumerSegment.length; i++) {
checkSelectedConsumerSegment[i] = false;
}
final TextView tv_ConsumerSegment = (TextView) findViewById(R.DropDownList.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment) {
// display all selected values
String selected = "";
int flag = 0;
for (int i = 0; i < consumerSegments.size(); i++) {
if (checkSelectedConsumerSegment[i] == true) {
selected += consumerSegments.get(i);
selected += ", ";
flag = 1;
}
}
if(flag == 1) {
tv_ConsumerSegment.setText(selected);
}
expandedConsumerSegment =true;
} else {
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.DropDownList.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment) {
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.DropDownList.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
here is my ConsumerSegmentListAdapter. The listview acts as my spinner.
public class ConsumerSegmentListAdapter extends BaseAdapter {
private ArrayList<String> mListCustomerSegment;
private LayoutInflater mInflater;
private TextView mSelectedItems;
private static int selectedCount = 0;
private static String firstSelected = "";
private ViewHolder holder;
private static String selected = ""; //shortened selected values representation
public static String getSelected() {
return selected;
}
public void setSelected(String selected) {
ConsumerSegmentListAdapter.selected = selected;
}
public ConsumerSegmentListAdapter(Context context, ArrayList<String> customerSegment,
TextView tv) {
mListCustomerSegment = new ArrayList<String>();
mListCustomerSegment.addAll(customerSegment);
mInflater = LayoutInflater.from(context);
mSelectedItems = tv;
}
#Override
public int getCount() {
return mListCustomerSegment.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.drop_down_customersegment, null);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.DropDownList.SelectOptionCustomerSegment);
holder.chkbox = (CheckBox) convertView.findViewById(R.DropDownList.checkboxCustomerSegment);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv.setText(mListCustomerSegment.get(position));
final int position1 = position;
//whenever the checkbox is clicked the selected values textview is updated with new selected values
holder.chkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setText(position1);
}
});
if(S_10th_IReportMain.checkSelectedConsumerSegment[position])
holder.chkbox.setChecked(true);
else
holder.chkbox.setChecked(false);
return convertView;
}
/*
* Function which updates the selected values display and information(checkSelectedConsumerSegment[])
* */
private void setText(int position1){
if (!S_10th_IReportMain.checkSelectedConsumerSegment[position1]) {
S_10th_IReportMain.checkSelectedConsumerSegment[position1] = true;
selectedCount++;
} else {
S_10th_IReportMain.checkSelectedConsumerSegment[position1] = false;
selectedCount--;
}
if (selectedCount == 0) {
mSelectedItems.setText(R.string.select_consumersegment);
} else if (selectedCount == 1) {
for (int i = 0; i < S_10th_IReportMain.checkSelectedConsumerSegment.length; i++) {
if (S_10th_IReportMain.checkSelectedConsumerSegment[i] == true) {
firstSelected = mListCustomerSegment.get(i);
break;
}
}
mSelectedItems.setText(firstSelected);
setSelected(firstSelected);
} else if (selectedCount > 1) {
for (int i = 0; i < S_10th_IReportMain.checkSelectedConsumerSegment.length; i++) {
if (S_10th_IReportMain.checkSelectedConsumerSegment[i] == true) {
firstSelected = mListCustomerSegment.get(i);
break;
}
}
mSelectedItems.setText(firstSelected + " & "+ (selectedCount - 1) + " more");
setSelected(firstSelected + " & "+ (selectedCount - 1) + " more");
}
}
private class ViewHolder {
TextView tv;
CheckBox chkbox;
}
}
I think You need to manage another storage for selected / unselected items and move it to the adapter. E.g. it can be HashSet<String>. Then code would look the following (note, that I made it compilable, because it's impossible to compile one provided in the question):
public class S_10th_IReportMain extends Activity {
boolean expandedConsumerSegment;
ConsumerSegmentListAdapter mAdapter;
private static class DatabaseHandler {
List<String> setItemOnConsumerSeg() {
return Collections.emptyList();
}
}
private static class BrandListAdapter {
static String getSelected() {
return "string";
}
}
DatabaseHandler databaseHandler = new DatabaseHandler();
private void initializeCustomerSegment() {
final ArrayList<String> consumerSegments = new ArrayList<String>();
List<String> consumerSegment = databaseHandler.setItemOnConsumerSeg();
consumerSegments.addAll(consumerSegment);
final TextView tv_ConsumerSegment = (TextView) findViewById(R.id.tv_ConsumerSegment);
tv_ConsumerSegment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!expandedConsumerSegment) {
// display all selected values
String selected = "";
int flag = 0;
for (String segment : consumerSegments) {
if (mAdapter.isChecked(segment)) {
selected += segment;
selected += ", ";
flag = 1;
}
}
if(flag == 1) {
tv_ConsumerSegment.setText(selected);
}
expandedConsumerSegment =true;
} else {
//display shortened representation of selected values
tv_ConsumerSegment.setText(BrandListAdapter.getSelected());
expandedConsumerSegment = false;
}
}
});
//onClickListener to initiate the dropDown list
TextView tv_customerSegment = (TextView)findViewById(R.id.tv_ConsumerSegment);
tv_customerSegment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
initiatePopUpCustomerSegment(consumerSegments,tv_ConsumerSegment);
}
});
}
PopupWindow pwConsumerSegment;
private void initiatePopUpCustomerSegment(ArrayList<String> customerSegments, TextView tv_CustomerSegment) {
LayoutInflater inflater = (LayoutInflater)S_10th_IReportMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get the pop-up window i.e. drop-down layout
LinearLayout layoutCustomerSegment = (LinearLayout)inflater.inflate(R.layout.pop_up_window_customersegment, (ViewGroup)findViewById(R.id.PopUpView1));
//get the view to which drop-down layout is to be anchored
RelativeLayout layout4 = (RelativeLayout)findViewById(R.id.relativeLayout4);
pwConsumerSegment = new PopupWindow(layoutCustomerSegment, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
//Pop-up window background cannot be null if we want the pop-up to listen touch events outside its window
pwConsumerSegment.setBackgroundDrawable(new BitmapDrawable());
pwConsumerSegment.setTouchable(true);
//let pop-up be informed about touch events outside its window. This should be done before setting the content of pop-up
pwConsumerSegment.setOutsideTouchable(true);
pwConsumerSegment.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
//dismiss the pop-up i.e. drop-down when touched anywhere outside the pop-up
pwConsumerSegment.setTouchInterceptor(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
pwConsumerSegment.dismiss();
return true;
}
return false;
}
});
//provide the source layout for drop-down
pwConsumerSegment.setContentView(layoutCustomerSegment);
//anchor the drop-down to bottom-left corner of 'layout1'
pwConsumerSegment.showAsDropDown(layout4);
//populate the drop-down list
final ListView listCustomerSegment = (ListView) layoutCustomerSegment.findViewById(R.id.dropDownCustomerSegment);
ConsumerSegmentListAdapter adapter = new ConsumerSegmentListAdapter(this, customerSegments, tv_CustomerSegment);
listCustomerSegment.setAdapter(adapter);
}
public static class ConsumerSegmentListAdapter extends BaseAdapter {
private ArrayList<String> mListCustomerSegment;
private LayoutInflater mInflater;
private TextView mSelectedItems;
private static int selectedCount = 0;
private static String firstSelected = "";
private ViewHolder holder;
private static String selected = ""; //shortened selected values representation
private HashSet<String> mCheckedItems;
public static String getSelected() {
return selected;
}
public void setSelected(String selected) {
ConsumerSegmentListAdapter.selected = selected;
}
public ConsumerSegmentListAdapter(Context context, ArrayList<String> customerSegment,
TextView tv) {
mListCustomerSegment = new ArrayList<String>();
mListCustomerSegment.addAll(customerSegment);
mInflater = LayoutInflater.from(context);
mSelectedItems = tv;
}
/**
* Should be called then new data obtained from DB
*
* #param checkedItems array of strings obtained from DB
*/
public void setCheckedItems(final String[] checkedItems) {
mCheckedItems.clear();
Collections.addAll(mCheckedItems, checkedItems);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mListCustomerSegment.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.drop_down_customersegment, null);
holder = new ViewHolder();
holder.tv = (TextView) convertView.findViewById(R.id.SelectOptionCustomerSegment);
holder.chkbox = (CheckBox) convertView.findViewById(R.id.checkboxCustomerSegment);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final String text = mListCustomerSegment.get(position);
final boolean checked = isChecked(text);
holder.tv.setText(mListCustomerSegment.get(position));
//whenever the checkbox is clicked the selected values textview is updated with new selected values
holder.chkbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setText(position, checked, text);
}
});
if(checked) {
holder.chkbox.setChecked(true);
} else {
holder.chkbox.setChecked(false);
}
return convertView;
}
/*
* Function which updates the selected values display and information(checkSelectedConsumerSegment[])
* */
private void setText(int position, boolean checked, String text){
if (!checked) {
mCheckedItems.add(text);
selectedCount++;
} else {
mCheckedItems.remove(text);
selectedCount--;
}
if (selectedCount == 0) {
mSelectedItems.setText(R.string.select_consumersegment);
} else if (selectedCount == 1) {
firstSelected = mCheckedItems.iterator().next();
mSelectedItems.setText(firstSelected);
setSelected(firstSelected);
} else if (selectedCount > 1) {
firstSelected = mCheckedItems.iterator().next();
mSelectedItems.setText(firstSelected + " & "+ (selectedCount - 1) + " more");
setSelected(firstSelected + " & "+ (selectedCount - 1) + " more");
}
}
/**
* #param segment to be checked
*
* #return true if the segment is checked
*/
public boolean isChecked(final String segment) {
return mCheckedItems.contains(segment);
}
private class ViewHolder {
TextView tv;
CheckBox chkbox;
}
}
}
So, then You obtain new data from database which should be checked You can just call mAdapter.setCheckedItems().
I already make it. By this:
for (int j=0; j<brands.size(); j++)
{
for(String chosenElement : Brands)
{
int index = brands.indexOf(chosenElement);
checkSelected[index] = true;
}
}
What I did is i look for the index of my chosen arraylist to my spinner's adapter and set the the checkbox index into true. That simple. Anyway thanks for the idea.

Adding a new row dynamically using a button

I am trying to add rows in a list view when a button is clicked , but my application is getting crashed everytime .
Here is my code :
public class MTCRichGraphicsActivity extends Activity {
int ELEMENT_COUNT = 3;
int position=0;
Button bAddView;
String[] elements = new String[ELEMENT_COUNT];
int r =0 ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bAddView = (Button) findViewById(R.id.bNewEvent);
final ListView list = (ListView) findViewById(R.id.list3d);
bAddView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.bNewEvent :
for (int i = 0; i< ELEMENT_COUNT; i++) {
elements[i] = String.valueOf(i);
}
final MyAdapter adapter = new MyAdapter(MTCRichGraphicsActivity.this,elements);
adapter.notifyDataSetChanged();
//list.setScrollY(currentPosition);
//list.setTranslationY(currentPosition);
list.setDivider( null );
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
ELEMENT_COUNT = ELEMENT_COUNT + 3;
}
}
});
}
}
Here I want to add 3 rows everytime a button(i.e. bNewEvent) is clicked , so I am incrementing ELEMENT_COUNT by 3 everytime. It works fine for first time , but when I press button second time it crashes.
Here is my adapter class :
public class MyAdapter extends BaseAdapter {
private final LayoutInflater mInflater;
private final String[] mItems;
TextView t;
ViewHolder holder;
public MyAdapter(Activity c,String[] objects) {
mInflater = c.getLayoutInflater();
mItems = objects;
}
public int getCount() {
return mItems.length;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView t;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem2, parent,false);
}
holder = new ViewHolder();
holder.t1 = (TextView) convertView.findViewById(R.id.tv1);
holder.t2 = (TextView) convertView.findViewById(R.id.tv2);
holder.t3 = (TextView) convertView.findViewById(R.id.tv3);
holder.t4 = (TextView) convertView.findViewById(R.id.tv4);
holder.t1.setText("Title"+position);
position = position + 3;
//((ImageView)convertView).setTextAlignment(1);
return convertView;
}
#Override
public Object getItem(int position) {
return mItems[position];
}
#Override
public long getItemId(int position) {
return position;
}
}
you can't use an array like this..
String[] elements = new String[ELEMENT_COUNT];
causes the array to have the same number of elements as the initial value of ELEMENT_COUNT, you can't then just increment ELEMENT_COUNT by 3 and try
for (int i = 0; i< ELEMENT_COUNT; i++) {
elements[i] = String.valueOf(i);
}
as the array only contains as many elements are initially defined. You need to change 'elements' to an ArrayList.
ArrayList<string> elements;
U define
int ELEMENT_COUNT = 3;
String[] elements = new String[ELEMENT_COUNT];
But u can't Resize Array
for (int i = 0; i< ELEMENT_COUNT; i++) {
elements[i] = String.valueOf(i);
}
this So u got Exception
Change Array To List
Like
List<String> element =new ArrayList<String>();
for (int i = 0; i< ELEMENT_COUNT; i++) {
element.add("String.valueOf(i)")
}
and Change Adapter also Like This

Categories

Resources