Adding a new row dynamically using a button - android

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

Related

How to fix "UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView"

I want to saveInstance when changing from portrait to landscape. But when I try to restoreInstance of my letter button's background and enable, it tells me this error.
The program went well when I comment out those codes.
This is letter class
public class Letter extends BaseAdapter {
private String[] letters;
private LayoutInflater letterInf;
public Letter(Context c){
letters = new String[26];
for(int a = 0; a < letters.length; a++){
letters[a] = ""+(char)(a+'A');
}
letterInf = LayoutInflater.from(c);
}
#Override
public int getCount() {
return letters.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Button btnLetter;
if(convertView == null){
btnLetter = (Button) letterInf.inflate(R.layout.letter, null, false);
}else{
btnLetter = (Button) convertView;
}
btnLetter.setText(letters[position]);
return btnLetter;
}
}
This is what I try to restore onRestoreInstance (the whole version)
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currPart = savedInstanceState.getInt("currPart");
numChars = savedInstanceState.getInt("numChars");
numCorr = savedInstanceState.getInt("numCorr");
int[] savedBodyPartVisibility = savedInstanceState.getIntArray("bodyPartVisibility");
for(int i = 0; i<savedBodyPartVisibility.length; i++){
bodyParts[i].setVisibility(savedBodyPartVisibility[i]);
}
//saved word
currWord = savedInstanceState.getString("currWord");
hint = savedInstanceState.getString("hint");
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){//get orientation
tvHint.setText("Hint:"+hint);// if landscape, show hint
//Toast.makeText(getBaseContext(), "This is landscape!", Toast.LENGTH_SHORT).show();
}
charViews = new TextView[currWord.length()];
wordLayout.removeAllViews();
for(int c = 0; c<currWord.length(); c++){
charViews[c] = new TextView(this);
charViews[c].setText(""+currWord.charAt(c));
charViews[c].setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
charViews[c].setGravity(Gravity.CENTER);
charViews[c].setTextColor(Color.WHITE);
charViews[c].setBackgroundResource(R.drawable.letter_bg);
wordLayout.addView(charViews[c]);
}
//saved charView
int[] savedCharViewColor = savedInstanceState.getIntArray("charViewColor");
for(int i = 0; i< savedCharViewColor.length; i++){
charViews[i].setTextColor(savedCharViewColor[i]);
}
//int numLetters = savedInstanceState.getInt("numLetters");
//letter enable//letter button background color
boolean[] savedLetterEnable = savedInstanceState.getBooleanArray("letterEnable");
int[] savedLettersColor = savedInstanceState.getIntArray("lettersColor");
for(int i = 0; i<savedLetterEnable.length; i++){
letters.getChildAt(i).setEnabled(savedLetterEnable[i]);
//letters.getChildAt(i).setBackgroundColor(savedLettersColor[i]);
}
}
You cannot restore it this way because views are recycled in RecyclerView/ListView. It means that only some of them is rendered and when you scroll it reuses already rendered views.
So in most of the cases it will not have that many child views as items in datasource.
The proper approach is to store information about items' state inside adapter.
I have created simple example to give you an idea how could it look. Note that setOnSelectedListener(new OnSelectedListener(){...} is fake code and you should write proper listener (onClick, or if you want to use Checkboxes then onCheckedCHange or anything else based on your needs).
public class Letter extends BaseAdapter {
private String[] letters;
private LayoutInflater letterInf;
private Set<String> selectedLetters = new ArraySet();
public Letter(Context c){
letters = new String[26];
for(int a = 0; a < letters.length; a++){
letters[a] = ""+(char)(a+'A');
}
letterInf = LayoutInflater.from(c);
}
Set<String> getState() {
return selectedLetters;
}
void restoreState(Set<String> selectedLetters) {
this.selectedLetters = selectedLetters;
notifyDataSetInvalidated();
}
#Override
public int getCount() {
return letters.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Button btnLetter;
if(convertView == null){
btnLetter = (Button) letterInf.inflate(R.layout.letter, null, false);
}else{
btnLetter = (Button) convertView;
}
if(selectedLetters.contains(letters[position])) {
btnLetter.setSelected(true);
} else {
btnLetter.setSelected(false);
}
btnLetter.setOnSelectedListener(new OnSelectedListener() {
void onSelected(..., boolean isSelected) {
if(isSelected) {
selectedLetters.add(letters[position]);
} else {
selectedLetters.remove(letters[position]);
}
}
});
btnLetter.setText(letters[position]);
return btnLetter;
}
}
Then whenever you save state, you get it from adapter getState and put it in savedInstanceState.
Whenever you restore state you get it from savedState and put in adapter restoreState

How to get listview items both visible and invisible child values

This loop return only visible position values.However I need the values of child items that are invisible.
for (int i = 0; i < material_issue_list.getCount(); i++) {
View layout = materialIssueAdapter.getViewByPositio(i, material_issue_list);
LinearLayout listItem = (LinearLayout) materialIssueAdapter.getViewByPositio(i, material_issue_list);
String batchSTR = ((AutoCompleteTextView) listItem.findViewById(R.id.batch_AutoComplete)).getText().toString();
String qtySTR = ((EditText) listItem.findViewById(R.id.issue_qty_ETD)).getText().toString();}
My full adapter class,Some one help me suggest to get the correct output.My problem I'm getting null values from the views that are invisible.
Only the visible values are being updated to arraylist.
Thanks in advance.
public class IssueMaterialAdapter extends BaseAdapter {
private Activity activity;
public static ArrayList Dummylist;
private static LayoutInflater inflater = null;
public Resources res;
public static ArrayList<BatchNav> batchNavs_Arr;
static ArrayList<String> batch_Arr;
public static ArrayList<String> batch_data;
public static ArrayList<String> issue_qty;
LinkedHashSet<String> hashSet;
public static ArrayList<BatchModel> batchModels = new ArrayList<BatchModel>();
public static HashMap<ViewHolder, String> batch_map;
public static HashMap<ViewHolder, String> qty_map;
HashMap<String, String> mValues = new HashMap<String, String>();
ArrayList<SaveDataModel> saveDataModels;
public IssueMaterialAdapter(Activity a, ArrayList dummy) {
activity = a;
Dummylist = dummy;
loadBatch();
this.batch_map = new HashMap<>();
inflater = (LayoutInflater) activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
if (Dummylist.size() <= 0)
return 1;
return Dummylist.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#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) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.material_issue_details_list, null);
holder = new ViewHolder();
holder.batch = (AutoCompleteTextView) vi.findViewById(R.id.batch_AutoComplete);
holder.issue = (EditText) vi.findViewById(R.id.issue_qty_ET);
holder.material_descrption = (TextView) vi.findViewById(R.id.material_desc);
holder.unit_issue = (EditText) vi.findViewById(R.id.unit_issue_ET);
holder.matnr = (TextView) vi.findViewById(R.id.matnr);
holder.prdgrp = (TextView) vi.findViewById(R.id.prod_grp);
vi.setTag(holder);
batch_map.put(holder, "");
FilterWithSpaceAdapter<String> farmer_co_no_adapter = new FilterWithSpaceAdapter<String>(activity,
R.layout.custom_items, batch_Arr);
holder.batch.setAdapter(farmer_co_no_adapter);
holder.batch.setThreshold(1);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (Dummylist.size() == AgriDistributionActivity.get_materials.size()) {
holder.material_descrption.setText(AgriDistributionActivity.get_materials.get(position));
holder.matnr.setText(AgriDistributionActivity.get_matnr.get(position));
holder.prdgrp.setText(AgriDistributionActivity.selected_prdgrp.get(position));
}
try {
if (saveDataArr.size() > 0) {
holder.batch.setText(saveDataArr.get(position).getBatch());
holder.issue.setText(saveDataArr.get(position).getQty());
holder.unit_issue.setText(saveDataArr.get(position).getQty_uom());
}
} catch (Exception e) {
}
return vi;
}
public static class ViewHolder {
public EditText issue, unit_issue;
public AutoCompleteTextView batch;
public TextView material_descrption, matnr,prdgrp;
}
private void loadBatch() {
batch_Arr = new ArrayList<String>();
batchNavs_Arr = new ArrayList<BatchNav>();
hashSet = new LinkedHashSet<>();
BatchNavEntityCollection batchNavEntityCollection = BatchNavEntityCollection.getInstance();
batchNavs_Arr = batchNavEntityCollection.getBatchOutVal();
for (int i = 0; i < batchNavs_Arr.size(); i++) {
String batch = batchNavs_Arr.get(i).getCharg();
batch_Arr.add(batch);
hashSet.addAll(batch_Arr);
batch_Arr.clear();
batch_Arr.addAll(hashSet);
}
}
public View getViewByPositio(int position, ListView listView) {
final int firstListItemPosition = listView.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;
if (position < firstListItemPosition || position > lastListItemPosition) {
return listView.getAdapter().getView(position, null, listView);
} else {
final int childIndex = position - firstListItemPosition;
return listView.getChildAt(childIndex);
}
}
}
You have saveDataArr list which holds all your data.
You can add a getter if you want to do it from an activity , add something like this to your adapter :
private SaveDataModelsendLog(int position) {
return saveDataArr(position);
}
That should do the trick , having said all that you should also look at the difference between static and non-static variables ,
it seems like you have to many of them ,
Enjoy.

Can a Shared Preference be applied to custom ListView?

I have a shared preference in my Custom list view. I am using it to keep numbers on the button but I have a condition where the row disappears when the button becomes 0 but when I scroll down it returns to its old form and becomes visible to it's user again. Is it possible to apply the same logic for view in SharedPreference like to keep last situation?
My code is the following:
import static android.view.View.INVISIBLE;
public class MainActivity extends Activity {
public MyAdapter adapter;
Context context;
public ListView list;
public int t[];
public SharedPreferences prefs;
public SharedPreferences.Editor edit;
int [] btnNums={100,150,94,72,206,489,1481,731,131,91,145,137,662,770,196,351,258,131,180,1281};
int[] images = {R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4, R.drawable.a5, R.drawable.a6, R.drawable.a7, R.drawable.a8, R.drawable.a9,
R.drawable.a10, R.drawable.a11, R.drawable.a12, R.drawable.a13, R.drawable.a14, R.drawable.a15, R.drawable.a16, R.drawable.a17, R.drawable.a18, R.drawable.a19, R.drawable.a20, R.drawable.a21};
String[] exp;
String[] mean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit= this.getSharedPreferences("NAME", Context.MODE_APPEND).edit();
prefs = getSharedPreferences("NAME", Context.MODE_APPEND);
Resources res=getResources();
exp= res.getStringArray(R.array.names);
mean=res.getStringArray(R.array.anlam);
list= (ListView) findViewById(R.id.listView);
//
// edit.putInt("Count", btnNums.length);
// int count = 0;
// for (int i: btnNums){
// edit.putInt("IntValue_" + count++, i);
// }
// edit.commit();
//
int[] ret;
int count1 = prefs.getInt("Count", 0);
ret = new int[count1];
for (int i = 0; i < count1; i++){
ret[i] =prefs.getInt("IntValue_"+ i, i);
}
t=ret;
if(t!=null)
{
adapter=new MyAdapter(this,exp,images,mean,t);
}else
{
adapter=new MyAdapter(this,exp,images,mean,btnNums);
}
list.setAdapter(adapter);
context=getApplicationContext();
}
}
class MyAdapter extends ArrayAdapter<String>{
int [] images;
String [] titleArray;
String [] descriptionArray;
int [] btnNums;
MainActivity ma;
public MyAdapter(MainActivity m, String[] titles, int imgs[], String[] descp, int[] btnNum ){
super(m, R.layout.single_row, R.id.textView,titles);
this.images=imgs;
this.titleArray=titles;
this.descriptionArray=descp;
btnNums=btnNum;
this.ma=m;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater= (LayoutInflater) ma.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View row=inflater.inflate(R.layout.single_row, parent, false);
final TextView myTitle=(TextView)row.findViewById(R.id.textView);
myTitle.findViewById(R.id.textView);
final TextView descp=(TextView)row.findViewById(R.id.textView2);
final ImageView imageView = (ImageView) row.findViewById(R.id.imageView);
final Button button = (Button) row.findViewById(R.id.angry_btn);
final Vibrator a = (Vibrator) ma.getSystemService(Context.VIBRATOR_SERVICE);
if(ma.t!=null)
{
for(int i=0; i<21;i++){
button.setText("" + ma.t[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}else
{
for(int i=0; i<21;i++){
button.setText("" + btnNums[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnNums[position]--;
storeIntArray(btnNums);
a.vibrate(30);
if (btnNums[position] == 0) {
button.setEnabled(false);
button.setVisibility(INVISIBLE);
row.setVisibility(INVISIBLE);
}
int temp[]=getFromPrefs();
ma.t=temp;
for (int i = 0; i < 21; i++) {
button.setText("" + temp[position]);
imageView.setImageResource(images[position]);
myTitle.setText(titleArray[position]);
descp.setText(descriptionArray[position]);
}
}
});
return row;
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
public void storeIntArray(int[] array){
ma.edit.putInt("Count", array.length);
int count = 0;
for (int i: array){
ma.edit.putInt("IntValue_" + count++, i);
}
ma.edit.commit();
}
public int[] getFromPrefs(){
int[] ret;
int count = ma.prefs.getInt("Count", 0);
ret = new int[count];
for (int i = 0; i < count; i++){
ret[i] =ma.prefs.getInt("IntValue_"+ i, i);
}
return ret;
}
}
First, please format your code, so its more readable.
Question: Can a Shared Preference be applied to custom ListView?
Answer: Yes it possible to use/access shared preferences in a Listview.
Upon reading your code, I believe the problem lies in your implementation of Listview and its adapter. The reason why it gets back to original state when scrolled down. Please note, that GetView is always called when scrolling.
You can refer to this topic: ListView & ViewHolder Pattern.

android - How to check how many elements are present in a GridView?

I am dynamically adding images to a GridView.
I want to have a counter to check how many images are present in a GridView.
The purpose is to restrict the user to add maximum of "n" images.
Therefore I want to have a counter which will count this number and I will check accordingly.
public class ExistingDetailedActivity extends Activity {
public String images,audiopath,name,assignedTo;
TextView ringtonename,assigned;
public GridView gridView;
public String [] imgpath;
CustomBaseExistAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_existing_detailed);
Intent i = getIntent();
if(i.hasExtra("BNDL")){
Bundle bdl = getIntent().getBundleExtra("BNDL");
if(bdl.get("IMAGEPATH") != null){
images = bdl.getString("IMAGEPATH");
}
if(bdl.get("AUDIOPATH") != null){
audiopath = bdl.getString("AUDIOPATH");
}
if(bdl.get("RINGTONENAME") != null){
name = bdl.getString("RINGTONENAME");
}
if(bdl.get("ASSIGNEDTO") != null){
assignedTo = bdl.getString("ASSIGNEDTO");
}
}
Typeface FONT_NAME = Typeface.createFromAsset(this.getAssets(), "komika-title-brush-1361511399.ttf");
imgpath=images.split("\\*") ;
ringtonename=(TextView) findViewById(R.id.textView2);
ringtonename.setText(name);
ringtonename.setTypeface(null, Typeface.BOLD);
ringtonename.setTypeface(FONT_NAME);
assigned=(TextView) findViewById(R.id.textView4);
assigned.setText(assignedTo);
assigned.setTypeface(null, Typeface.BOLD);
assigned.setTypeface(FONT_NAME);
gridView=(GridView) findViewById(R.id.gridview1);
adapter = new CustomBaseExistAdapter(this,imgpath);
//adapter.notifyDataSetChanged();
gridView.invalidateViews();
gridView.setAdapter(adapter);
}
}
Another one is
public class CustomBaseExistAdapter extends BaseAdapter{
private final Activity context;
public String[] imagepath;
private String[] imagepath1=null;
private String[] imagepathBackUp=null;
public CustomBaseExistAdapter(Activity context,
String[] imagepath) {
this.context = context;
this.imagepath = imagepath;
this.imagepathBackUp =imagepath;
List<String> nonBlank = new ArrayList<String>();
for(String s: imagepath) {
if (!s.trim().isEmpty()) {
nonBlank.add(s);
}
}
imagepath1 = (String[]) nonBlank.toArray( new String[nonBlank.size()] );
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return imagepath.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public int getItemViewType(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
convertView = null;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.custom_image_with_checkbox, null);
CheckBox cb=(CheckBox) convertView.findViewById(R.id.checkBox1);
final ImageView imageView = (ImageView) convertView.findViewById(R.id.imgThumb);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
int id = buttonView.getId();
if(isChecked){
/*String newList[] = new String[imagepath.length - 1];
int count = 0;
for (int i = 0; i < imagepath.length; i++) {
if (imagepath.length - 1 > 0) {
if (imagepath[i] == imagepath1[position]) { // itemPath[1] as the range starts from 0, so 1 would be ITEM2
// SKIP IF MATCHES THE ITEM YO WANT TO REMOVE
} else {
newList[count] = imagepath[i];
count++;
}
}
}
imagepath=new String[newList.length];
imagepath= newList;*/
List<String> newlist= new ArrayList<String>(Arrays.asList(imagepath));
newlist.remove(imagepath1[position]);
imagepath=null;
imagepath = newlist.toArray(new String[newlist.size()]);
/*new String[newlist.size()];
for(int j =0;j<newlist.size();j++){
imagepath[j] = newlist.get(j);
}*/
notifyDataSetChanged();
}
}
});
imageView.setImageBitmap(BitmapFactory.decodeFile(imagepath[position]));
}
return convertView;
}
}
To know number of Elements in GridView, here ,
put int count = (position + 1); in your GridView Adapter getView(..) method. It is callback method, called number of times to populate your Gridview. Starts from 0.
int count = 0; // define count as global instance var.
public View getView(final int position, View convertView, ViewGroup parent){
...
count = position + 1;
...
}
count is what you want.

Looping through ListView twice

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.

Categories

Resources