I am trying to figure this out, but i just cant see what i am doing wrong. I want to dynamically fill ListView with products (add product to array then refresh list, basically for every click add one product to array then display content of array in ListView) which is in 2nd fragment with the data from the first Fragment. Passing Data is working (used Log to confirm), but my main problem is updating the ListView which has custom adapter. With this code nothing is happening (ViewList is not refreshing, I can see every log (and everything else works) and no errors).
Here is the code (All this is in 2nd Fragment):
This code is global
ReceiptListAdapter receiptListAdapter;
ArrayList<ReceiptItem> receiptItemArrayList;
int cat = 0;
int prodct = 0;
With this i get 2 numbers from 1st fragment (to this 2nd fragment)
public void use(int num1, int num2) {
Log.d("LOG","Category: " + num1 + "Product: " + num2); //This works
cat = num1;
prodct = num2;
ListView receiptItemListView = (ListView) getView().findViewById(
R.id.receiptItemsList);
receiptItemArrayList = (ArrayList<ReceiptItem>)generateReceiptItemsForTest();
receiptItemListView.setAdapter(receiptListAdapter); //i think here is the problem
receiptListAdapter.notifyDataSetChanged();
}
OnViewCreated
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView receiptItemListView = (ListView) getView().findViewById(
R.id.receiptItemsList);
receiptItemArrayList = (ArrayList<ReceiptItem>) generateReceiptItemsForTest();
receiptListAdapter = new ReceiptListAdapter(
getActivity().getBaseContext(), R.layout.receipt_item,
receiptItemArrayList);
receiptItemListView.setAdapter(receiptListAdapter);
TextView txtTotalAmmount = (TextView) getView().findViewById(
R.id.txtReceiptTotalAmmount);
double totalAmmount = getTotalAmmount(receiptItemArrayList);
totalAmmount = Math.round(totalAmmount * 100) / 100;
txtTotalAmmount.append(String.valueOf(totalAmmount));
}
private List<ReceiptItem> generateReceiptItemsForTest() {
List<ReceiptItem> receiptItemList = new ArrayList<ReceiptItem>();
DatabaseAdapter db = new DatabaseAdapter(getActivity());
if(cat != 0 && prodct != 0 )
{
name = db.readFromCategoriesAndGetOnePreduct(cat, prodct).getName();
price = db.readFromCategoriesAndGetOnePreduct(cat, prodct).getPrice();
Log.d("Name: " + name,"Price: " + String.valueOf(price)); //Also working (showing what i want) and i can see it in log but the ListView isnt refreshing this data
receiptItemList.add(new ReceiptItem(name,1,price,1);
}
}
return receiptItemList;
}
private double getTotalAmmount(ArrayList<ReceiptItem> receiptItems) {
double totalAmmount = 0;
for (ReceiptItem receiptItem : receiptItems) {
totalAmmount += receiptItem.getTotalPrice();
}
return totalAmmount;
}
ReceiptListAdapter
public class ReceiptListAdapter extends ArrayAdapter<ReceiptItem> {
private Context context;
public ReceiptListAdapter(Context context, int rowResourceId,
ArrayList<ReceiptItem> items) {
super(context, rowResourceId, items);
this.context = context;
}
#SuppressWarnings("deprecation")
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.receipt_item, null);
}
ReceiptItem item = getItem(position);
if (item != null) {
TextView itemDescription = (TextView) view
.findViewById(R.id.txtReceiptItemDescription);
TextView itemAmmount = (TextView) view
.findViewById(R.id.txtReceiptItemAmmount);
TextView itemPrice = (TextView) view
.findViewById(R.id.txtReceiptItemPrice);
TableRow listItem = (TableRow) view
.findViewById(R.id.trReceiptItem);
if (position % 2 == 0)
listItem.setBackgroundDrawable(view.getResources().getDrawable(
R.drawable.list_item_selector_a));
else
listItem.setBackgroundDrawable(view.getResources().getDrawable(
R.drawable.list_item_selector_b));
itemDescription.setText(item.getDescription());
itemAmmount.setText(String.valueOf(item.getAmmount()));
itemPrice.setText(String.format("%.2f", item.getPrice()));
}
return view;
}
}
Only time I got the list to update is when I used this code
receiptListAdapter = new ReceiptListAdapter(getActivity().getBaseContext(),R.layout.receipt_item,
instead of
receiptItemListView.setAdapter(receiptListAdapter);
But it only adds one time and refreshes the list again on click, but i know why.
Can you post the ReceiptListAdapter code? That is where you need to make the connection between the data source and the UI. You do this by registering ContentObservers on the database and then the ListView registers its ContentObserver with the Adapter. The Adapter notifies the ListView to update by calling the onChanged() method of the ListView DataSetObserver.
When working with a database, a common choice is to use a CursorLoader to fetch the data from the database on a background thread paired with a CursorAdapter. The CursorLoader automatically registers with the database to be notified of changes. You then implement the LoaderManager callbacks which tell you when the dataset changes and passes you an updated cursor. You then call swapCursor(cursor) on the CursorAdapter, passing it the new cursor and it notifies the ListView DataSetObserver that the dataset has changed. The ListView then queries the adapter to get the new values and refreshes the UI.
Check out this tutorial for some good example code: http://www.vogella.com/tutorials/AndroidSQLite/article.html
I figured it out i had to make this global List<ReceiptItem> receiptItemList = new ArrayList<ReceiptItem>(); Also I would like to thank middleseatman for explaining some things, it really helped me.
Related
Currently I'm trying to send intent data from user input to display onto my custom adapter. The intent data from user input from the detailspage.java class will be sent to the listview page with custom Arrayadapter. However each time i add a new item it overwrites my previous entries. Hope some kind souls can help someone new to android.
Below are snippets of my code.
// Set a click listener on that button
btnAddData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveExercise(exerciseName);
}
});
}
private void saveExercise(String name) {
// Read from input fields
// Use trim to eliminate leading or trailing white space
String setString = mSetEditText.getText().toString().trim();
String repString = mRepEditText.getText().toString().trim();
String nameString = name;
Intent intent = new Intent(ExerciseDetailActivity.this, WorkoutSetActivity.class);
intent.putExtra("name", nameString);
intent.putExtra("set", setString);
intent.putExtra("rep", repString);
startActivity(intent);
}
The intent data will be sent to the activity page to initiate the custom ArrayAdapter.
public class WorkoutSetActivity extends AppCompatActivity {
ArrayList<WorkoutSet> workout = new ArrayList<WorkoutSet>();
/** Adapter for the ListView */
WorkoutSetAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.exercise_list);
adapter = new WorkoutSetAdapter(this, workout);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
Intent intent = this.getIntent();
String name = intent.getExtras().getString("name");
String set = intent.getExtras().getString("set");
String rep = intent.getExtras().getString("rep");
adapter.add(new WorkoutSet(name,set,rep));
Toast.makeText(WorkoutSetActivity.this, "Workout added.", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
}
Lastly the custom ArrayAdapter code. This is where I set the custom listview.
public class WorkoutSetAdapter extends ArrayAdapter<WorkoutSet> {
public WorkoutSetAdapter(Activity context, ArrayList<WorkoutSet> workout) {
super(context, 0, workout);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if the existing view is being reused, otherwise inflate the view
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.activity_workout_set, parent, false);
}
WorkoutSet currentWorkout = getItem(position);
// Find individual views that we want to modify in the list item layout
TextView nameTextView = (TextView) listItemView.findViewById(R.id.workout_name);
TextView setTextView = (TextView) listItemView.findViewById(R.id.workout_set);
TextView repTextView = (TextView) listItemView.findViewById(R.id.workout_rep);
nameTextView.setText(currentWorkout.getName());
setTextView.setText("Sets: "+ currentWorkout.getSet());
repTextView.setText("Reps: "+ currentWorkout.getRep());
return listItemView;
}
}
each time i add a new item it overwrites my previous entries
There are no "previous entries". startActivity loads an empty adapter each time and you only add one element.
What you want is a SQLite database (or any persistent storage layer, but SQLite is provided without more libraries).
On the plus side, your Intent and Adapter code look fine.
Every time,you call startActivity (), you open a new WorkoutSetActivity, it's a new WorkoutSetActivity object instance, so the arrayAdapter is also new one, it will only display the data you send this time.
If you want to display all the data, you must save the previous data to database or file. At WorkoutSetActivity onCreate (), you should get the previous data, put them and current data to the adapter.
Background
Hi, I am new to Android and trying to get familiar with ListView. So I decide to write a simple program for user to enter quotes and display them in order. I implement a StringAdapter and call the notifyDataSetChanged every time when the user confirms.
Question
The weird thing is that the ListView would sometimes update the oldest quotes and sometimes the newer one. and I don't know the problem.
Please ignore the view data button. In this state, I have entered four quotes:
Quotes: hi - Signature:William Shakespeare
Quotes: hello - Signature:William Shakespeare
Quotes: Virtue is bold and goodness never fearful. - Signature:William Shakespeare
Quotes: Love all, trust a few, do wrong to none. - Signature:William Shakespeare
(in reverse order, meaning in time sequence, it goes 4,3,2,1)
Code
main activity
public class storage extends AppCompatActivity {
// the adapter
private StringAdapter sa;
// the edit text view
public EditText etString,etSignature;
// the list view
public ListView lv;
// the array list to capture the quotes and signature
private ArrayList<String[]> dataString = new ArrayList<String[]>();
// add the string and notify
public void addString(String[] s){
this.dataString.add(0,s);
((BaseAdapter)this.lv.getAdapter()).notifyDataSetChanged();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_storage);
// Link the view elements
this.etString = (EditText) findViewById(R.id.etInput);
this.etSignature = (EditText) findViewById(R.id.etSignature);
this.lv = (ListView) findViewById(R.id.stringList);
Button btn_confirm = (Button) findViewById(R.id.btnConfirm),
btn_viewData = (Button) findViewById(R.id.btnViewData);
// load the adapter
this.sa = new StringAdapter(this,this.dataString);
lv.setAdapter(sa);
btn_confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
storage s = (storage) v.getContext();
// get the String
String sString = s.etString.getText().toString(),
sSignature = s.etSignature.getText().toString();
System.out.println("Quotes: " + sString + "\nSignature:" + sSignature);
// verify it is not empty
if (!sString.isEmpty()&&!sSignature.isEmpty()) {
// add new string and notify
s.addString(new String[]{s.etString.getText().toString(),
s.etSignature.getText().toString()});
((StringAdapter) s.lv.getAdapter()).print_stringData();
// prompt the result
Toast.makeText(s.getBaseContext(),
"Enter Quotes from"+etSignature.getText().toString(),Toast.LENGTH_SHORT).show();
} else {
// prompt the result
Toast.makeText(s.getBaseContext(),
"Please Enter Quotes and Signatures!",Toast.LENGTH_SHORT).show();
}
}
});
}
}
StringAdapter
public class StringAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String[]> dataStrings = new ArrayList<String[]>();
public StringAdapter(Context c,ArrayList<String[]> dataStrings){this.mContext=c;this.dataStrings=dataStrings;}
public int getCount(){return this.dataStrings.size();}
public Object getItem(int position){ return this.dataStrings.get(position);}
public long getItemId(int postion){ return (long) postion;}
public void print_stringData(){
System.out.println("String Adapter Output:");
for(String [] s: this.dataStrings){
System.out.println("Quotes: "+s[0]+"\nSignature:"+s[1]);
}
}
public View getView(int position, View convertView, ViewGroup parent){
LinearLayout ll;
if(convertView == null){
// set the linear layout
ll = new LinearLayout(this.mContext);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
// get the data and set the text inside
String[] data = this.dataStrings.get(position);
TextView //tvNo = new TextView(this.mContext),
tvString = new TextView(this.mContext),
tvSignature = new TextView(this.mContext);
ll.addView(tvString);
ll.addView(tvSignature);
tvString.setText(data[0]);
tvString.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
tvSignature.setText(data[1]);
tvSignature.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
tvSignature.setGravity(Gravity.RIGHT);
}
else{
ll = (LinearLayout) convertView;
}
return ll;
}
}
Comments
Some might notice that I add the String[] always to the first element. Actually I have tried to add to the last. The weird behavior still exists.
Environment
Android SDK Version: API 23 lollipop
Emulator Version: Nexus S API 23
Yes, of course, you get that error. Why? Because ListView always re-use convertView in your getView function of Adapter.
Look at your if,else:
else{
ll = (LinearLayout) convertView;
}
return ll;
At this block, you tell the adapter reuse the convertView, but you dont re-set the data. As a result, it will show the data of the previous row.
How to resolve it? just set the data in else block as you do in if one.
P/s: you should learn how to use ViewHolder in ListView to avoid laggy in when scrolling.
I have a listview with a custon adapter. I the row's layout, I have a text and a checkbox.
When I load the listview, I get the data from a database and it has one colunm that determine if the row is cheched or not. When I load the list, its ok, the rows that has to stay checked, stays checkd, and the others no. The problem is: when I unckheck a row ans roll the list down and up, when I return to the start, the row that I had unchecked, returns checked again, how can I resold this problem:
The getView() code below:
public View getView(int index, View view, ViewGroup parent) {
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.linha_acessorios, parent, false);
}
final AcessoriosItensLista acessorios = (AcessoriosItensLista)getItem(index);
final ImageView imgAcessorio = (ImageView)view.findViewById(R.id.imgAcessorioLista);
final CheckBox cb = (CheckBox)view.findViewById(R.id.cbListaAcessorios);
TextView tvNome = (TextView) view.findViewById(R.id.tvNomeAcessoriosLinha);
tvNome.setText(acessorios.getNomeAcessorio());
final Integer iditem = Integer.valueOf(acessorios.getId());
boolean ch = acessorios.isChecked();
final Integer position = Integer.valueOf(index);
if(ch){
if(!checked.contains(iditem)){
checkedPositions.add(position);
checked.add(iditem);
}
}
cb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(checked.contains(iditem)){
checked.remove(iditem);
checkedPositions.remove(position);
}
if (((CheckBox) v).isChecked()) {
checkedPositions.add(position);
checked.add(iditem);
int id = context.getResources().getIdentifier("acc_gold_"+acessorios.getId(), "drawable", context.getPackageName());
imgAcessorio.setBackgroundResource(id);
}
else if(checkedPositions.contains(position)) {
checkedPositions.remove(position);
checked.remove(iditem);
int id = context.getResources().getIdentifier("acc_"+acessorios.getId(), "drawable", context.getPackageName());
imgAcessorio.setBackgroundResource(id);
}
}
});
if(checkedPositions.contains(position)){
cb.setChecked(true);
int id = context.getResources().getIdentifier("acc_gold_"+acessorios.getId(), "drawable", context.getPackageName());
imgAcessorio.setBackgroundResource(id);
} else {
cb.setChecked(false);
int id = context.getResources().getIdentifier("acc_"+acessorios.getId(), "drawable", context.getPackageName());
imgAcessorio.setBackgroundResource(id);
}
return view;
}
My guess is that probably you're unchecking that CheckBox but you're not saving its status anywhere, so when that row disappears from the screen by scrolling and you scroll down again, it loads the data again from the database and it's checked in it. I don't know how you're handling your ArrayAdapter extension, but I recommend saving the constructor's ArrayList as an instance inside the class, updating that value inside of it on uncheck, and call notifyDataSetChanged().
---- EDIT ----
To store the ArrayList inside your class, you'll have to create a separate class (with the two fields you're working on), for example:
class MyRow {
CheckBox cb;
TextView tv;
}
So when you declare your custom adapter in your Activity, you'll have to declare previously an ArrayList with some initial elements (or even empty):
ArrayList<MyRow> myList = new ArrayList<MyRow>();
MyRow row1 = new MyRow();
row1.cb.isChecked(...);
row1.tv.setText(...);
myList.add(row1);
Then you call the constructor of your adapter class, something like this:
MyArrayAdapter adapter = new MyArrayAdapter(context, R.layout.your_layout, myList);
So when you pass it to the constructor of your adapter class, you save a copy of it in that class:
public class MyArrayAdapter extends ArrayAdapter {
final private ArrayList<MyRow> myContent;
...
MyArrayAdapter(Context context, int my_layout, ArrayList<MyRow> myContent_) {
...
myContent = myContent_
}
}
So now, any content you change (like for example checking/unchecking a checkbox) you have to save its state in the myContent array. You would find that item by getItem(position) in your getView() method and make the changes you need. After it, you just have to call the notifyDataSetChanged(); method and it will automatically display the changes in your ListView.
It's almost as it your list items are being re-redered or recreated when they go off screen, now the easiest and obvious solution here is to trigger an event when your checkbox is clicked so make an onclick event in your adapter that is triggered when the checkbox is checked or unchecked and updates the data source.
I am developing an app in which I need a ListView whose rows have a TextView, 2 CheckBox and a Spinner.
However, I am experiencing issues with onItemSelected() of the Spinner, as it gets called each time it is displayed for each row. In this method I am updating database records with the selected option, but as Android calls it automatically, every time the items get reset because Android calls it with position 0 and this is the value updated in the database.
I have read a lot of links about the issue with onItemSelected() and some hacks, but all of them are to use without a ListView. Any points here?
I have tried to track in a List which positions are actually displayed to make it work but it does not. I think it is because of the recycling in Android that causes the troubleshooting method get called for Spinners already shown!
So the point is: How can I differenciate a real call to onItemSelected() because of a user selection from the Android call when displaying the Spinner?
Here is the code of my adapter that extends SimpleCursorAdapter.
Thank you so much in advance.
public ParticipationAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
mActivity = (Activity)context;
ParticipationComment.ParticipationCommentManager commentManager = new ParticipationComment.ParticipationCommentManager(mActivity);
mParticipationCommentsCursor = commentManager.get();
mActivity.startManagingCursor(mParticipationCommentsCursor);
commentManager.detach();
mPositionsOfCursorIds = getPositionsOfCursorIds(mParticipationCommentsCursor);
mSpinnerPositionsDisplayed = new ArrayList<Integer>();
}
#Override
public View getView(final int participationPosition, View convertView, ViewGroup parent) {
final Cursor participationsCursor = getCursor();
mActivity.startManagingCursor(participationsCursor);
participationsCursor.moveToPosition(participationPosition);
View participationRow;
if (convertView == null) {
participationRow = LayoutInflater.from(mActivity).inflate(R.layout.participation_row_student, null);
} else {
mSpinnerPositionsDisplayed.remove((Integer)convertView.getTag());
participationRow = convertView;
}
participationRow.setTag(participationPosition);
Spinner commentSpinner = (Spinner)participationRow.findViewById(R.id.participation_comment_id_spinner);
SimpleCursorAdapter commentSpinnerAdapter = new SimpleCursorAdapter(
mActivity,
android.R.layout.simple_spinner_item,
mParticipationCommentsCursor,
new String[] {DatabaseManager.NAME},
new int[] {android.R.id.text1}
);
commentSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
commentSpinner.setAdapter(commentSpinnerAdapter);
long participationCommentId = participationsCursor.getLong(participationsCursor.getColumnIndex(DatabaseManager.PARTICIPATION_COMMENT_ID));
if (participationCommentId != 0) {
commentSpinner.setSelection(mPositionsOfCursorIds.get(participationCommentId));
}
commentSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
participationsCursor.moveToPosition(participationPosition);
if (!mSpinnerPositionsDisplayed.contains(participationPosition)) {
// Android calls this method the first time a Spinner is displayed,
// to differentiate from a real user click we check if the current Spinner's position
// in the ListView is being shown
mSpinnerPositionsDisplayed.add(participationPosition);
} else {
ParticipationComment participationComment = new ParticipationComment((Cursor)parent.getItemAtPosition(position));
Participation.ParticipationManager participationManager = new Participation.ParticipationManager(mActivity);
Participation participation = new Participation(participationsCursor);
participation.setConnectionProfileParticipationCommentId(participationComment.getConnectionProfileId());
participation.setParticipationCommentId(participationComment.getIdOpenErp());
participation.setChanged(true);
participationManager.update(participation);
participationManager.detach();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Not used
}
});
TextView studentName = (TextView)participationRow.findViewById(R.id.participation_student_name);
studentName.setText(participationsCursor.getString(participationsCursor.getColumnIndex(DatabaseManager.NAME)));
CheckBox expectedPresent = (CheckBox)participationRow.findViewById(R.id.participation_expected_present_value);
expectedPresent.setChecked(participationsCursor.getInt(participationsCursor.getColumnIndex(DatabaseManager.EXPECTED_PRESENT)) == 1);
CheckBox present = (CheckBox)participationRow.findViewById(R.id.participation_present_value);
present.setChecked(participationsCursor.getInt(participationsCursor.getColumnIndex(DatabaseManager.PRESENT)) == 1);
return participationRow;
}
A better way is to use a AlertDialog Variant.. like this.. and create a button which initially has the first selection as its Text and its changed based on the AlertDialog choice..
What about using a small flag to discard first call of ItemSelected ?
I am displaying the Data in to ListView as like below code:
private class OrderAdapter extends ArrayAdapter<Employer> {
private ArrayList<Employer> items;
public OrderAdapter(Context context, int textViewResourceId, ArrayList<Employer> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.paye_list_row, null);
}
Employer o = items.get(position);
if (o != null) {
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.value);
if (tt != null) {
tt.setText(o.getOrderName()); // Setting the Value here
}
if(bt != null){
if(position==0)
bt.setText(o.getTaxcode()); // Setting the Value here
if(position==1)
bt.setText(o.getPayPeriod()); // Setting the Value here
if(position==2)
bt.setText(o.getPayFrequency()); // Setting the Value here
if(position==3)
bt.setText(o.getSalaryWage()); // Setting the Value here
if(position==4)
bt.setText(o.getNetGrossAmount()); // Setting the Value here
if(position==5)
bt.setText(o.getKiwiSaverMember()); // Setting the Value here
if(position==6)
bt.setText(o.getEmployeeDeduction()); // Setting the Value here
if(position==7)
bt.setText(o.getEmployeeContribution()); // Setting the Value here
if(position==8)
bt.setText(o.getComplyingFundMember()); // Setting the Value here
if(position==9)
bt.setText(o.getFundContribution()); // Setting the Value here
if(position==10)
bt.setText(o.getESCTTaxRate()); // Setting the Value here
if(position==11)
bt.setText(o.getChildSupportDeduction()); // Setting the Value here
if(position==12)
bt.setText(o.getPayrollDonation()); // Setting the Value here
}
}
return v;
}
}
And i am adding the data manualy to my another ArrayList like below code:
// Set Employee one by one
ArrayList<Employer> tempEmployerList = employerList;
System.out.println("=================================" +
"=IN end Document================================");
System.out.println(" tempEmployerList Size:" +tempEmployerList.size());
Employer m = new Employer();
// My Code for to add data
m = new Employer();
m.setTaxcode(taxCodeValue);
m.setPayPeriod(payPeriodValue);
m.setPayFrequency(payFrequencyValue);
m.setSalaryWage(salaryWageValue);
m.setNetGrossAmount("Gross");
m.setKiwiSaverMember(kiwiSaverMemberValue);
m.setEmployeeDeduction(employeeDeductionValue);
m .setEmployeeContribution(employeeContributionValue);
m.setComplyingFundMember(complyingFundMemberValue);
m.setFundContribution(fundContributionValue);
m.setESCTTaxRate(ESCTTaxRateValue);
m.setChildSupportDeduction(childSupportDeductionValue);
m.setPayrollDonation(payrollDonationValue);
employerList.add(m);
If I want to display that data in log cat then i can see it by below code:
// TO DISPLAY DATA
for(int j=0;j<tempEmployerList.size();j++)
{
System.out.println("================ Employee: "+(j+1)+"======================");
m = new Employer();
m=tempEmployerList.get(j);
//System.out.println("TaxCodeHeading: "+(j+1)+" = "+m.getOrderName());
System.out.println("TaxCode: "+(j+1)+" = "+m.getTaxcode());
System.out.println("PayPeriod: "+(j+1)+" = "+m.getPayPeriod());
System.out.println("Frequency: "+(j+1)+" = "+m.getPayFrequency());
System.out.println("Salary/Wage: "+(j+1)+" = "+m.getSalaryWage());
System.out.println("NetGross Amount: "+(j+1)+" = "+m.getNetGrossAmount());
System.out.println("KiwiSaverMember: "+(j+1)+" = "+m.getKiwiSaverMember());
System.out.println("Employee Deduction: "+(j+1)+" = "+m.getEmployeeDeduction());
System.out.println("Complying Fund Member: "+(j+1)+" = "+m.getComplyingFundMember());
System.out.println("Fund Contribution: "+(j+1)+" = "+m.getFundContribution());
System.out.println("ESCT Tax Rate: "+(j+1)+" = "+m.getESCTTaxRate());
System.out.println("Child Support Deduction: "+(j+1)+" = "+m.getChildSupportDeduction());
System.out.println("Payroll giving Donation: "+(j+1)+" = "+m.getPayrollDonation());
}
All Works fine. But now if i have added more then one employee then i want to display it on the List view one by one on the click of the next button click.
So how it is Possible.
Please help me for that.
Thanks.
Declare an Employee Object as a Field in Activity, and load your adapter data from that field, in case of next and previous button event change Employer object to next or previous item in list and call adapter.notifyDataSetChanged() method.
It appears that you're trying to use a ListView to display different values of the employer object. This is a misuse of the ListView, which is generally used to display a collection of arbitrary length, with similar entities represented by each row in the list.
In this case, you would be better to simply create a simple form of vertically stacked label & field widgets. These could be placed into a ScrollView so that the whole thing could be larger than the display area. The prev / next buttons would simply update this form with the current employer information. This approach would be much simpler and more efficient than a ListView.