i am adding data to list view it shows multiple Times .
I have two Activities.first activity i have add button and listview . when i click add button i goes to second activity.in second activity,adding data to ArrayList.here i am passing arraylist object to first Activity using parcelable .
in first activity,here i am storing the getting ArrayList object values in one Arraylist<>.and then passing object to listview. in listview data showing in multipule times .please go though this link https://www.codota.com/codebox/#/9lqy1ardnfyctyb9/shared
please, sorry i am not good in english.
public class MainActivity extends ActionBarActivity {
ImageView addView, searchView;
DetailsEmp detailsEmp = new DetailsEmp();
ListView listView;
ArrayList<Employee> listDetails=new ArrayList<Employee>();
DetailsAdapter detailsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Employee emp = (Employee) getIntent().getParcelableExtra(detailsEmp.PAR_KEY);
listView = (ListView) findViewById(R.id.listView);
addView = (ImageView) findViewById(R.id.addImage);
addView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), DetailsEmp.class);
startActivity(i);
}
});
if (emp != null) {
Employee emplyoee=new Employee();
{
emplyoee.setName(emp.getName());
listDetails.add(emplyoee);
emplyoee.setCmpny(emp.getCmpny());
listDetails.add(emplyoee);
emplyoee.setDisig(emp.getDisig());
listDetails.add(emplyoee);
emplyoee.setListAge(emp.getListAge());
listDetails.add(emplyoee);
emplyoee.setListGen(emp.getListGen());
listDetails.add(emplyoee);
emplyoee.setListExp(emp.getListExp());
listDetails.add(emplyoee);
Log.d("bundle Size is ", "Emp Name is " + emp.getName());
Log.d("bundle Size is ", "Emp Sex is " + emp.getListGen());
Log.d("list Size is ", " ArrayList<Emplyoee> " + listDetails.size());
for (int i = 0; i < listDetails.size(); i++) {
Log.d("list Size is ", " ArrayList<Emplyoee> "
+ listDetails.get(i).getName().toString());
}
}
detailsAdapter=new DetailsAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, listDetails);
listView.setAdapter(detailsAdapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
// second activity
public class DetailsAdapter extends ArrayAdapter<Employee> {
private Context context;
private ArrayList<Employee> listDetails;
public DetailsAdapter(Context context, int resource,
ArrayList<Employee> listDetails) {
super(context, resource, listDetails);
// TODO Auto-generated constructor stub
this.context = context;
this.listDetails = listDetails;
}
private class ViewHolder
{
TextView empName,empCmpny,empDisig,empAge,empExp ;
ImageView empIcon;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder=null;
Employee emplyoee=getItem(position);
LayoutInflater inflator=(LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if(convertView == null)
{
convertView =inflator.inflate(R.layout.activity_listview, parent, false);
holder=new ViewHolder();
holder.empName=(TextView)convertView.findViewById(R.id.listName);
holder.empCmpny=(TextView)convertView.findViewById(R.id.listCmpny);
holder.empDisig=(TextView)convertView.findViewById(R.id.listDesignation);
holder.empIcon=(ImageView)convertView.findViewById(R.id.female);
convertView.setTag(holder);
}
holder=(ViewHolder)convertView.getTag();
for (int j = 0; j < listDetails.size(); j++) {
holder.empName.setText(emplyoee.getName());
holder.empCmpny.setText(emplyoee.getCmpny());
holder.empDisig.setText(emplyoee.getDisig());
if (emplyoee.getListGen().toString() == "Male") {
holder.empIcon.setImageResource(R.drawable.client_male_dark);
}
}
return convertView;
}
}
// POJO class
public class Employee implements Parcelable {
String listName = null;
String listCmpny = null;
String listDisig = null;
String listExp = null;
String listAge = null;
String listGen = null;
public String getName() {
return listName;
}
public String getListExp() {
return listExp;
}
public void setListExp(String listExp) {
this.listExp = listExp;
}
public String getListAge() {
return listAge;
}
public void setListAge(String listAge) {
this.listAge = listAge;
}
public String getListGen() {
return listGen;
}
public void setListGen(String listGen) {
this.listGen = listGen;
}
public void setName(String listName) {
this.listName = listName;
}
public String getCmpny() {
return listCmpny;
}
public void setCmpny(String listCmpny) {
this.listCmpny = listCmpny;
}
public String getDisig() {
return listDisig;
}
public void setDisig(String listDisig) {
this.listDisig = listDisig;
}
public static final Parcelable.Creator CREATOR = new Creator() {
#Override
public Employee createFromParcel(Parcel source) {
Employee emp = new Employee();
emp.listName = source.readString();
emp.listCmpny = source.readString();
emp.listDisig = source.readString();
emp.listAge = source.readString();
emp.listGen = source.readString();
emp.listExp = source.readString();
return emp;
}
public Employee[] newArray(int size) {
return new Employee[size];
}
};
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(listName);
dest.writeString(listCmpny);
dest.writeString(listDisig);
dest.writeString(listAge);
dest.writeString(listGen);
dest.writeString(listExp);
}
}
// DetailsEmp
public class DetailsEmp extends Activity {
public final static String PAR_KEY="key_par";
private EditText empName, empCmpny, empDisig, empAge, empExp;
private RadioGroup empGender;
private RadioButton empMale, empFemale;
Button save;
ArrayList<Employee> list = new ArrayList<Employee>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_emp);
// getting the details from the xml
empName = (EditText) findViewById(R.id.editName);
empCmpny = (EditText) findViewById(R.id.editCmpny);
empDisig = (EditText) findViewById(R.id.editDisignation);
empAge = (EditText) findViewById(R.id.editAge);
empExp = (EditText) findViewById(R.id.editExp);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
empGenderDetails();
}
});
}
protected void empGenderDetails() {
// TODO Auto-generated method stub
// empMale = (RadioButton) findViewById(R.id.male);
Employee emp = new Employee();
emp.setName(empName.getText().toString());
//list.add(emp);
emp.setCmpny(empCmpny.getText().toString());
//list.add(emp);
emp.setDisig(empDisig.getText().toString());
//list.add(emp);
emp.setListAge(empAge.getText().toString());
//list.add(emp);
emp.setListExp(empExp.getText().toString());
//list.add(emp);
empFemale = (RadioButton) findViewById(R.id.female);
empGender = (RadioGroup) findViewById(R.id.radioGroup);
int sel = empGender.getCheckedRadioButtonId();
empMale = (RadioButton) findViewById(sel);
emp.setListGen(empMale.getText().toString());
Log.d("Employee data ", " Emp " + emp.listName.toString()
+ empMale.getText().toString()
+ empExp.getText().toString());
Intent i = new Intent(getApplicationContext(),
MainActivity.class);
Bundle b=new Bundle();
b.putParcelable(PAR_KEY , emp);
i.putExtras(b);
//setResult(RESULT_OK, i);
startActivity(i);
finish();
//list.add(emp);
Log.d("Emplyooe Size ","Emplyoee " + emp.getName());
/*
}
emplyoee.setName(emp.getName());
listDetails.add(emplyoee);
emplyoee.setCmpny(emp.getCmpny());
listDetails.add(emplyoee);
emplyoee.setDisig(emp.getDisig());
listDetails.add(emplyoee);
emplyoee.setListAge(emp.getListAge());
listDetails.add(emplyoee);
emplyoee.setListGen(emp.getListGen());
listDetails.add(emplyoee);
emplyoee.setListExp(emp.getListExp());
listDetails.add(emplyoee);
you keep adding a new emplyoee (mispelled btw, but that's up to you), you need to do
emplyoee.setName(emp.getName());
emplyoee.setCmpny(emp.getCmpny());
emplyoee.setDisig(emp.getDisig());
emplyoee.setListAge(emp.getListAge());
emplyoee.setListGen(emp.getListGen());
emplyoee.setListExp(emp.getListExp());
listDetails.add(emplyoee);
or:
addView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
emplyoee.setName(emp.getName());
emplyoee.setCmpny(emp.getCmpny());
emplyoee.setDisig(emp.getDisig());
emplyoee.setListAge(emp.getListAge());
emplyoee.setListGen(emp.getListGen());
emplyoee.setListExp(emp.getListExp());
listDetails.add(emplyoee);
Intent i = new Intent(getApplicationContext(), DetailsEmp.class);
startActivity(i);
}
});
Your way of using Adapter is quite a immature one. Please On click of the save button add your "emp" object to the ArrayList and don't recreate the adapter once again when your dataset is changed just notify it the data has changed. Have a method as given below in your adapter rather then having the data supply in the constructor.
public void setData(ArrayList<Employee> _listOfEmp){
this.listOfEmp = _listOfEmp;
}
and then notify the adapter in your activity when ever you change the dataset.
For your clarity.
Read this:
http://developer.android.com/reference/android/widget/ArrayAdapter.html
and see this example:
http://www.vogella.com/tutorials/AndroidListView/article.html
Related
I'm trying to make a laundry ordering application. I've made it to the order process, at the end of the order process, the user clicks the next button to checkout the ordered results, I have successfully made the checkout results, but what I made is still in one variable string. how to put the checkout results into an array variable so that I can post the results in the form of JSONArray?
HERE IS MY ORDER ACTIVITY CODE :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_produk);
// menghubungkan variablel pada layout dan pada java
listProduk = (ListView)findViewById(R.id.list_produk);
swipeProduct = (SwipeRefreshLayout)findViewById(R.id.swipeProduct);
radioExpress = (RadioButton)findViewById(R.id.radio_express);
radioReguler = (RadioButton)findViewById(R.id.radio_regular);
tvTotal = (TextView)findViewById(R.id.total);
next = (Button)findViewById(R.id.button_next);
actionBar = getSupportActionBar();
laundry_id = getIntent().getStringExtra(TAG_LAUNDRY_ID);
// untuk mengisi data dari JSON ke dalam adapter
productAdapter = new CheckboxAdapter(this, (ArrayList<ProductModel>) productList, this);
listProduk.setAdapter(productAdapter);
listProduk.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
productAdapter.setCheckBox(position);
}
});
// menampilkan widget refresh
swipeProduct.setOnRefreshListener(this);
swipeProduct.post(new Runnable() {
#Override
public void run() {
swipeProduct.setRefreshing(true);
productList.clear();
tvTotal.setText(String.valueOf(0));
radioReguler.isChecked();
regular = true;
productAdapter.notifyDataSetChanged();
callProduct();
}
}
);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Menu Yang Dipilih");
dialog.setCancelable(true);
txtnamaProduk = (TextView) dialogView.findViewById(R.id.txtNama_produk);
txtnamaProduk.setText(hasil);
dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
AND HERE IS THE CODE OF THE RESULT :
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
}
in my code above, I still use the variable checkbox to accommodate all the results of the order chosen by the user. how to put all the result into array variable so i can post to server as a JSONArray? Please help me to solve this problem. because i'm still a beginner in android.
HERE IS MY ADAPTER CODE IF NEEDED :
public class CheckboxAdapter extends BaseAdapter{
private Context context;
private ArrayList<ProductModel> productItems;
ProdukLaundry produk;
public CheckboxAdapter(Context context, ArrayList<ProductModel> items, ProdukLaundry produk) {
this.context = context;
this.productItems = items;
this.produk = produk;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return productItems.size();
}
#Override
public Object getItem(int position) {
return productItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder viewHolder;
final ProductModel items = productItems.get(position);
if(view == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_produk, null, true);
viewHolder.checkBox = (CheckBox) view.findViewById(R.id.checkBox_productName);
viewHolder.decrease = (TextView) view.findViewById(R.id.decrease_product);
viewHolder.count = (TextView) view.findViewById(R.id.count_product);
viewHolder.increase = (TextView) view.findViewById(R.id.increase_product);
viewHolder.price = (TextView) view.findViewById(R.id.product_price);
view.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.checkBox.setText(items.getProduct_name());
viewHolder.price.setText(items.getProduct_price());
viewHolder.count.setText(String.valueOf(items.getCountProduct()));
//fungsi untuk set posisi textview + dan -
viewHolder.increase.setTag(R.integer.btn_plus_view, view);
viewHolder.increase.setTag(R.integer.btn_plus_pos, position);
viewHolder.decrease.setTag(R.integer.btn_minus_view, view);
viewHolder.decrease.setTag(R.integer.btn_minus_pos, position);
//fungsi untuk disable textview + dan - jika checkbox tidak di klik
viewHolder.decrease.setOnClickListener(null);
viewHolder.increase.setOnClickListener(null);
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
viewHolder.increase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View) viewHolder.increase.getTag(R.integer.btn_plus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.increase.getTag(R.integer.btn_plus_pos);
int countProduct = Integer.parseInt(tv.getText().toString()) + 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.tambah(pos);
}
});
viewHolder.decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View tempview = (View)viewHolder.decrease.getTag(R.integer.btn_minus_view);
TextView tv = (TextView) tempview.findViewById(R.id.count_product);
Integer pos = (Integer) viewHolder.decrease.getTag(R.integer.btn_minus_pos);
int total = productItems.get(pos).getCountProduct();
if (total>0){
int countProduct = Integer.parseInt(tv.getText().toString()) - 1;
tv.setText(String.valueOf(countProduct));
productItems.get(pos).setCountProduct(countProduct);
produk.kurang(pos);
}
}
});
} else {
viewHolder.checkBox.setChecked(false);
//fungsi untuk reset jumlah harga dan produk pada checkbox
String count = viewHolder.count.getText().toString();
int jumlah = Integer.parseInt(count);
int harga = Integer.parseInt(productItems.get(position).getProduct_price());
int kurang = jumlah * harga;
viewHolder.count.setText("0");
productItems.get(position).setCountProduct(0);
produk.kurangCheckbox(kurang);
}
return view;
}
public ArrayList<ProductModel> getAllData(){
return productItems;
}
public void setCheckBox(int position){
ProductModel items = productItems.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
static class ViewHolder{
TextView decrease, count, increase, price;
CheckBox checkBox;
}
}
just create getter setter method of Arraylist like below
CompleteOrder:-
public class CompleteOrder {
List<OrderItem> order_items;
public List<OrderItem> getOrder_items() {
return order_items;
}
public void setOrder_items(List<OrderItem> order_items) {
this.order_items = order_items;
}
}
Create another Getter setter class of variable you want to add in arraylist
OrderItem:-
public class OrderItem {
String product_name;
int product_total;
public OrderItem(String product_name, int product_total) {
this.product_name = product_name;
this.product_total = product_total;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_total() {
return product_total;
}
public void setProduct_total(int product_total) {
this.product_total = product_total;
}
}
Now in your onClick method just create new List as below
public void onClick(View view) {
String checkbox = "";
CompleteOrder completeOrder=new CompleteOrder();
List<OrderItem> masterProductorderCount=new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
masterProductorderCount.add(new OrderItem(holder.getProduct_name(),total);
}
}
completeOrder.setOrder_items(masterProductorderCount);
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(completeOrder);//pass object of CompleteOrder
}
});
CompleteOrder object give JSON output as below
{
"CompleteOrder":[
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
},
{
"product_name":"your product name",
"product_total":1
}
]
}
make a model that contains product name , total and etc,
then put each data into an object and put each object into an array
finally use Gson to map properties to model / list of models or the other way around.
ArrayList<Model> list = new ArrayList<>();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
Model model = new Model();
model.productName = hold.getProduct_name();
model.total = total;
list.add(model);
}
}
String jsonArray = Gson().toJson(list);
You need to create a JSONObject for each entry in the JSONArray.
As far as I can see this should take care of it:
public void onClick(View view) {
String checkbox = "";
JSONArray jsonArray = new JSONArray();
for (ProductModel hold : productAdapter.getAllData()) {
int total = Integer.parseInt(hold.getProduct_price())*(hold.getCountProduct());
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getProduct_name() + " " + total;
JSONObject jsonObj = new JSONObject();
jsonObj.put("product_name", hold.getProduct_name());
jsonObj.put("product_total", total);
jsonArray.put(jsonObj);
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
String jsonArrayString = jsonArray.toString();
formSubmit(dipilih);
}
Depending on your data the resulting string from jsonArrayString would be:
{[
{"product_name":"product1","product_total":1},
{"product_name":"product2","product_total":2},
{"product_name":"product3","product_total":3}
]}
I really do not know what you intend on doing with the JSON data so I just created a String "jsonArrayString".. do what ever you need to with it.
I made a custom adapter that displays objects in Listview and an icon for each item in list. There are 3 icons that show next to an item in the list view. User can select option "Kupljeno" which changes Status of object to 1, option "Nije kupljeno" to 0 and "Nije dostupno" to 2. Each number represents a different icon, you can that in getView() function of Adapter class. The adapter class looks like this:
public class ListaAdapter extends ArrayAdapter<Proizvod> {
public ListaAdapter(Context context, ArrayList<Proizvod> proizvodi) {
super(context, 0, proizvodi);
}
public void remove(int position) {
this.remove(getItem(position));
}
public View getView(int position, View convertView, ViewGroup parent) {
Proizvod proizvod = getItem(position);
if(convertView==null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.shoppinglista_prikazproizvoda,parent,false);
TextView t = (TextView)convertView.findViewById(R.id.text1);
t.setText(proizvod.toString());
switch(proizvod.getStatus())
{
case 0:
t.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_nijekupljeno, 0);
break;
case 1:
t.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_kupljeno, 0);
break;
case 2:
t.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.ic_nedostupno, 0);
break;
}
}
return convertView;
}
}
You can see that I set icon of each item in getView().
The user should be able to change Status of each Proizvod object with a context menu and when the user chooses object Status, the list should update and show the appropriate icon.
My Proizvod class is this:
public class Proizvod {
private int id;
private String naziv;
private int kolicina=1;
private double cijena;
private String lista;
public int status=0; //0 - nije kupljeno, 1 - kupljeno, 2 - nedostupno
public Proizvod() {
}
public Proizvod(int id, String naziv, int kolicina, double cijena, String lista, int status) {
this.id = id;
this.naziv = naziv;
this.kolicina = kolicina;
this.cijena = cijena;
this.status = status;
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
public int getKolicina() {
return kolicina;
}
public void setKolicina(int kolicina) {
this.kolicina = kolicina;
}
public double getCijena() { return cijena; }
public void setCijena(double cijena) {
this.cijena = cijena;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLista() { return lista; }
public void setLista(String lista) { this.lista = lista; }
public int getStatus() { return status; }
public void setStatus(int status) { this.status = status; }
#Override
public String toString() {
if(this.kolicina==1) {
return this.naziv + " ["+ this.kolicina +" komad, ukupno " + this.cijena + " kn ]";
}
else {
return this.naziv + " ["+ this.kolicina +" komada, ukupno " + this.cijena + " kn ]";
}
}
}
The code for context menu and changing icon (activity):
public class KreiranjeListeActivity extends AppCompatActivity {
ArrayList<Proizvod> ShoppingLista = new ArrayList<Proizvod>();
EditText nazivProizvoda;
EditText kolicina;
EditText cijena;
Button dodaj;
Button ocisti;
Button spremi;
ListView lista;
ListaAdapter adapter;
//Funkcija vraća ukupan iznos svih stavki u listi
public void AzurirajUkupniTrosak() {
DecimalFormat zaokruzi=new DecimalFormat("0.00");
double ukupniIznos=0;
for(Proizvod p : ShoppingLista)
{
ukupniIznos+=p.getCijena();
}
String ukupniIznosString=zaokruzi.format(ukupniIznos);
TextView prikazUkupnogIznosa=(TextView)findViewById(R.id.textView_ukupaniznos);
prikazUkupnogIznosa.setText("Ukupno: " + ukupniIznosString + " kn");
}
//Funkcija otvara meni dužim pritiskom na stavku u listi i nudi opciju brisanja stavke
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
if (v.getId() == R.id.shoppinglista2_list) {
ListView lv = (ListView) v;
AdapterView.AdapterContextMenuInfo acmi = (AdapterView.AdapterContextMenuInfo) menuInfo;
Proizvod proizvod = (Proizvod) lv.getItemAtPosition(acmi.position);
menu.add(200,201,1,"Obriši");
menu.add(200,202,2,"Kupljeno");
menu.add(200,203,3,"Nije kupljeno");
menu.add(200,204,4,"Proizvod je nedostupan");
menu.add(200,205,5,"Zatvori prozor");
}
}
//funkcija u kojoj se sa adaptera briše odabrana stavka, iste promjene se automatski primijene i na listu
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case 201:
adapter.remove(info.position);
adapter.notifyDataSetChanged();
AzurirajUkupniTrosak();
return true;
case 202:
ShoppingLista.get(info.position).setStatus(1);
adapter.notifyDataSetChanged();
return true;
case 203:
ShoppingLista.get(info.position).setStatus(0);
adapter.notifyDataSetChanged();
return true;
case 204:
ShoppingLista.get(info.position).setStatus(2);
adapter.notifyDataSetChanged();
return true;
}
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kreiranje_liste);
final DBHandler db = new DBHandler(this);
nazivProizvoda=(EditText)findViewById(R.id.nazivproizvoda_text);
kolicina=(EditText)findViewById(R.id.kolicinaproizvoda_text);
cijena=(EditText)findViewById(R.id.cijenaproizvoda_text);
dodaj=(Button)findViewById(R.id.dodaj_gumb);
ocisti=(Button)findViewById(R.id.ocisti_gumb);
spremi=(Button)findViewById(R.id.spremi_gumb);
lista=(ListView)findViewById(R.id.shoppinglista2_list);
registerForContextMenu(lista);
adapter = new ListaAdapter(this,ShoppingLista);
lista.setAdapter(adapter);
dodaj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/////////////PROVJERE KOD UPISA ///////////////////////
if(TextUtils.isEmpty(nazivProizvoda.getText())) {
nazivProizvoda.setError("Unesite naziv proizvoda!");
return;
}
if(TextUtils.isEmpty(cijena.getText())) {
cijena.setError("Unesite cijenu!");
return;
}
if(TextUtils.isEmpty(kolicina.getText())) {
kolicina.setError("Unesite količinu!");
return;
}
if((kolicina.getText().toString()).contains(".")) {
kolicina.setError("Unesite ispravan broj!");
return;
}
/////////////PROVJERE KOD UPISA -KRAJ ////////////////////////
DecimalFormat zaokruzi=new DecimalFormat("0.00");
Proizvod p = new Proizvod();
p.setNaziv(nazivProizvoda.getText().toString());
p.setKolicina(Integer.parseInt(kolicina.getText().toString()));
String ukupnaCijena=zaokruzi.format(Float.parseFloat(cijena.getText().toString())*Integer.parseInt(kolicina.getText().toString())).toString();
p.setCijena(Double.parseDouble(ukupnaCijena)); //množi se količina sa cijenom jednog komada proizvoda
ShoppingLista.add(p);
adapter.notifyDataSetChanged();
AzurirajUkupniTrosak();
Toast.makeText(getApplicationContext(), "Proizvod dodan u listu!",
Toast.LENGTH_SHORT).show();
nazivProizvoda.setText("");
kolicina.setText("");
cijena.setText("");
}
});
ocisti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShoppingLista.clear();
adapter.notifyDataSetChanged();
AzurirajUkupniTrosak();
Toast.makeText(getApplicationContext(), "Proizvodi su obrisani!",
Toast.LENGTH_SHORT).show();
}
});
spremi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(KreiranjeListeActivity.this);
View promptsView = li.inflate(R.layout.spremanje_liste, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
KreiranjeListeActivity.this);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText nazivListe = (EditText) promptsView
.findViewById(R.id.nazivListe);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Spremi",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
ShoppingLista shoppinglista = new ShoppingLista(nazivListe.getText().toString(),"TEST DATUMA");
/////POSTAVLJANJE UKUPNOG IZNOSA U NOVOSTVORENU LISTU
DecimalFormat zaokruzi=new DecimalFormat("0.00");
double ukupniIznos=0;
for(Proizvod p : ShoppingLista)
{
ukupniIznos+=p.getCijena();
}
//////////////////////////////////////////////////////
db.dodajListu(shoppinglista);
for(Proizvod p : ShoppingLista)
{
db.dodajProizvod(p,nazivListe.getText().toString());
}
Intent i = new Intent(KreiranjeListeActivity.this, PopisListaActivity.class);
startActivity(i);
}
})
.setNegativeButton("Otkaži",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
}
The problem is that the icons don't change at all. The value of Status of a selected object changes but the icon doesn't, even though I use adapter.notifyDataSetChanged(); What's wrong?
Here change this in your code in your List adapter class:
First create a list of type Proizvod
List<Proizvod> dataList = new ArrayList<>();
then
public ListaAdapter(Context context, ArrayList<Proizvod> proizvodi) {
super(context, 0, proizvodi);
this.dataList = proizvodi;
}
In place of Proizvod proizvod = getItem(position);
use
Proizvod proizvod = dataList.getItem(position);
Hope it helps!!!
I'm new to Java and Android and am trying to figure out how to write a ListView and load the ListView from where it is saved.
I have ListView and each item on the ListView has a string and bool that changes if a checkbox for the item is checked or unchecked. I have a working method to add items to the ListView and am now trying to figure out how to write the ListView to a textfile.
I got some code for saving the ListView by clicking a menu item and them I'm trying to load it when I re-run the program in my OnCreate, but nothing is loading. I'm not sure if its the write or load that is not working or both.
Here is a class I made that works with my ListView.
Item.java
public class Item {
String name;
boolean isChecked = false;
public Item(String name) {this.name = name;}
public Item(String name, boolean checked){
this.name = name;
this.isChecked = checked;
}
#Override
public String toString(){
return name;
}
}
Here is my MainActivity.java that includes my saveList() and readFile()
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getName();
ArrayList<Item> items = new ArrayList<>();
private ListView lv;
private static final String sFile = "Saved.txt";
protected ListView getListView() {
if (lv == null) {
lv = (ListView) findViewById(android.R.id.list);
}
return lv;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter) adapter).getWrappedAdapter();
} else {
return adapter;
}
}
private void deleteList()
{
if (!items.isEmpty())
{
items.clear();
}
lv.invalidateViews();
}
private void deleteCheckedItems()
{
SparseBooleanArray checked = lv.getCheckedItemPositions();
for(int i = 0; i < lv.getCount(); i++)
{
if (checked.get(i)==true)
{
items.remove(i);
}
lv.invalidateViews();
}
lv.clearChoices();
}
private void saveList(ArrayList<Item> itemlist) {
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput(sFile, 0));
int iCnt = 0;
String allstring = "";
for (Item s : items)
{
if (s.isChecked)
{
iCnt++;
if (iCnt < items.size()) {
String thisstring;
thisstring = s.name + "\r\n";
out.write(thisstring);
allstring += thisstring;
} else {
String thisstring;
thisstring = s.name;
out.write(thisstring);
allstring += thisstring;
}
}
}
out.close();
//Toast.makeText(activity, allstring + " Written", duration).show();
}
catch (java.io.FileNotFoundException e)
{
}
catch (Exception ex)
{
// Toast.makeText(activity, "Write Exception : " + ex.getMessage(), duration).show();
}
}
public String readFile(ArrayList<Item> itemsList)
{
String sRet = "Nothing";
try
{
InputStream is = openFileInput(sFile);
if (is != null)
{
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String sLine;
StringBuffer sb = new StringBuffer();
while ((sLine = br.readLine()) != null)
sb.append(sLine + "\r\n");
is.close();
sRet = sb.toString();
// Toast.makeText(Toast.LENGTH_LONG).show();
}
}
catch (java.io.FileNotFoundException e)
{
}
catch (Exception ex)
{
// Toast.makeText(activi"Read Exception" + ex.getMessage(), Toast.LENGTH_LONG).show();
}
return sRet;
}
private void addItemDialog()
{
LayoutInflater inflater = LayoutInflater.from(this);
final View addView = inflater.inflate(R.layout.add, null);
new AlertDialog.Builder(this)
.setTitle("Add Item")
.setView(addView)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText txtAdd = (EditText) addView.findViewById(R.id.etInput);
String sItem = (txtAdd).getText().toString();
items.add(new Item(sItem));
for (int i = 0; i < items.size(); i++)
{
lv.setItemChecked(i, items.get(i).isChecked);
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setListAdapter(new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_multiple_choice, items));
lv = this.getListView();
for (int i = 0; i < items.size(); i++)
{
lv.setItemChecked(i, items.get(i).isChecked);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
readFile(items);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.add_item:
addItemDialog();
return true;
case R.id.clear_all:
deleteList();
return true;
case R.id.clear_checked:
deleteCheckedItems();
return true;
case R.id.write:
saveList(items);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
put your oncreate method above after declaration that means after this line
private static final String sFile = "Saved.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.......
.......
//your code
}
//other method
Read Android activity lifecyle for better understanding
I have arraylists. I want the data from that arraylist. I am not getting the data. instead when i use arraylist.get(i) i get the whole arraylist.
Here is my code
This the main activity where onlick of listview item i am getting the values and passing it to next activity using putStringArrayListExtra.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String varr = history.get(position).getLati().toString();
ArrayList<String>clicklat=new ArrayList<String>();
clicklat.add(varr);
String var2 = history.get(position).getLongi().toString();
ArrayList<String>clicklong=new ArrayList<String>();
clicklong.add(var2);
String var3 = history.get(position).getDatetime().toString();
ArrayList<String>dttime=new ArrayList<String>();
dttime.add(var3);
Intent i = new Intent(HistoryActivity.this, DetailsActivity.class);
i.putStringArrayListExtra("clicklat", clicklat);
i.putStringArrayListExtra("clicklong", clicklong);
i.putStringArrayListExtra("clickdatetime", dttime);
startActivity(i);
}
});
Here is DetailsActivity
public class DetailsActivity extends AppCompatActivity {
private Toolbar toolbar;
String latitudee;
String longitudee;
String dateetime;
ArrayList<String> newLat;
ArrayList<String> newLong;
ArrayList<String> newDateTime;
ArrayList<DetailsPojo> details;
DetailsPojo detailsPojo;
DetailsAdapter adapter;
ListView detList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("History Details");
Intent intent = getIntent();
details = new ArrayList<DetailsPojo>();
newLat = new ArrayList<>();
newLong = new ArrayList<>();
newDateTime = new ArrayList<>();
newLat = intent.getStringArrayListExtra("clicklat");
newLong = intent.getStringArrayListExtra("clicklong");
newDateTime = intent.getStringArrayListExtra("clickdatetime");
for (int i = 0; i < newLat.size(); i++) {
detailsPojo = new DetailsPojo();
latitudee = newLat.get(i);
longitudee = newLong.get(i);
dateetime = newDateTime.get(i);
Log.e("detais latitude", "" + latitudee);
Log.e("detailos longitudee", "" + longitudee);
Log.e("detailos datetimeee", "" + dateetime);
detailsPojo.setDetailsdatetime(dateetime);
detailsPojo.setDetailslat(latitudee);
detailsPojo.setDetailslong(longitudee);
}
details.add(detailsPojo);
detList = (ListView) findViewById(R.id.detailsList);
adapter = new DetailsAdapter(DetailsActivity.this, details);
detList.setAdapter(adapter);
}
and this is DetailsAdapter
public class DetailsAdapter extends BaseAdapter {
private Context activity;
TextView dt_datetime;
TextView dt_lat;
TextView dt_long;
ArrayList<DetailsPojo> list;
private ArrayList<DetailsPojo> arraylist = null;
public static LayoutInflater inflater;
private Context context;
public DetailsAdapter(Context a, ArrayList<DetailsPojo> details) {
// TODO Auto-generated constructor stub
activity = a;
list = details;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist = new ArrayList<DetailsPojo>();
this.arraylist.addAll(list);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if(convertView == null) {
v = inflater.inflate(R.layout.details_item, parent, false);
}
final DetailsPojo pojo = list.get(position);
dt_datetime = (TextView) v.findViewById(R.id.detailsdatetime);
dt_lat = (TextView) v.findViewById(R.id.detailslat);
dt_long = (TextView) v.findViewById(R.id.detailslong);
dt_datetime.setText(pojo.getDetailsdatetime());
dt_lat.setText(pojo.getDetailslat());
dt_long.setText(pojo.getDetailslong());
return v;
}
}
This is the arraylist
latitude﹕ [21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121776, 21.121774, 21.121774]
UPDATE:
this is getLati and getLongi
public List<String> getLati(){
return this.lat;
}
public List<String> getLongi(){
return this.longi;
}
public void setLati(List<String> lat){
this.lat = lat;
}
public void setLongi(List<String> longi){
this.longi = longi;
}
Is there anything wrong? Please help me.
Try this code:
protected void onCreate(Bundle savedInstanceState) {
...
for (int i = 0; i < newLat.size(); i++) {
DetailsPojo detailsPojo = new DetailsPojo(); //changes here
latitudee = newLat.get(i);
longitudee = newLong.get(i);
dateetime = newDateTime.get(i);
Log.e("detais latitude", "" + latitudee);
Log.e("detailos longitudee", "" + longitudee);
Log.e("detailos datetimeee", "" + dateetime);
detailsPojo.setDetailsdatetime(dateetime);
detailsPojo.setDetailslat(latitudee);
detailsPojo.setDetailslong(longitudee);
details.add(detailsPojo); // and here
}
detList = (ListView) findViewById(R.id.detailsList);
adapter = new DetailsAdapter(DetailsActivity.this, details);
detList.setAdapter(adapter);
}
I've declared detailsPojo object inside the loop instead of a global variable.
PS: Make sure newLong and newDateTime have the same size as newLat to avoid IndexOutOfBoundsException.
UPDATE:
Change your click listener to:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ArrayList<String>clicklat= new ArrayList<String>(history.get(position).getLati());
ArrayList<String>clicklong= new ArrayList<String>(history.get(position).getLongi());
ArrayList<String>dttime= new ArrayList<String>(history.get(position).getDatetime());
Intent i = new Intent(HistoryActivity.this, DetailsActivity.class);
i.putStringArrayListExtra("clicklat", clicklat);
i.putStringArrayListExtra("clicklong", clicklong);
i.putStringArrayListExtra("clickdatetime", dttime);
startActivity(i);
}
Try this code in HereActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
...
for (int i = 0; i < newLat.size(); i++) {
DetailsPojo detailsPojo = new DetailsPojo();
latitudee = newLat.get(i);
longitudee = newLong.get(i);
dateetime = newDateTime.get(i);
Log.e("detais latitude", "" + latitudee);
Log.e("detailos longitudee", "" + longitudee);
Log.e("detailos datetimeee", "" + dateetime);
detailsPojo.setDetailsdatetime(dateetime);
detailsPojo.setDetailslat(latitudee);
detailsPojo.setDetailslong(longitudee);
details.add(detailsPojo); // move it to here
}
// details.add(detailsPojo); // remove it
detList = (ListView) findViewById(R.id.detailsList);
adapter = new DetailsAdapter(DetailsActivity.this, details);
detList.setAdapter(adapter);
}
....
Hope this help
I think the problem here is that you are creating your lists inside the onClick listener. This means that everytime the user clicks a new List is created and then the value added. So you will always end up with 1 size lists. And if you are trying to use get() on a 1 size list you are getting the only element a.k.a. the whole list. Just move the instructions like:
ArrayList<String>clicklat=new ArrayList<String>();
outside the listener and you should be ok.
I'm facing an odd situation here, when I search for an item it returns me what I'm searching for, but it is doing something else too, it is adding 2 empty rows to the listview by each character pressed on the search, if I search for example: "fire" it will add 8 empty rows at the end of my listview, why is this happening?
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class FragmentClientes extends Fragment implements OnQueryTextListener{
private boolean searchCheck;
private List<ClienteModel> clientes = new ArrayList<ClienteModel>();
private ListView lv;
private View rootView;
ProgressBar progressBar;
private LinearLayout footerLinearLayout;
public FragmentActivity activity;
private SearchView searchView;
private String currentQuery = null;
private ClientViewAdapter ad;
private ClientSearchViewAdapter ads;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
rootView = inflater.inflate(R.layout._fragment_clientes, container, false);
rootView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT ));
return rootView;
}
public void gerarToast(CharSequence message) {
int duration = Toast.LENGTH_LONG;
Toast toast = Toast
.makeText(getActivity(), message, duration);
toast.show();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu, menu);
searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(Menus.PROCURAR));
if (searchView != null) {
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
public boolean onQueryTextSubmit(String submit) {
// showResults(submit, 1);
return false;
}
public boolean onQueryTextChange(String change) {
//TODO Auto-generated method stub
if (searchCheck) {
showResults();
try {
clientes = new ArrayList<ClienteModel>();
Repositorio mRepositorio = new Repositorio(getActivity());
List Clientes = mRepositorio.getClientes(change, 15, 1);
clientes = Clientes;
ads = new ClientSearchViewAdapter(getActivity(), this, clientes);
lv.addFooterView(footerLinearLayout);
lv.setOnScrollListener(new EndlessScrollListener() {
#Override
public void onLoadMore(int page, int totalItemsCount) {
new LoadMoreClientTask(progressBar, FragmentClientes.this, ad, getActivity()).execute(1);
System.out.println("PAGE " + page);
}
});
new LoadMoreClientTask(progressBar, this, ad, getActivity()).execute(1);
lv.setAdapter(ads);
System.out.println("Pesquisa: " + clientes);
}catch (Exception e){
e.printStackTrace();
}
}
return false;
}
});
}
searchView.setQueryHint(this.getString(R.string.search));
((EditText)searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text))
.setHintTextColor(getResources().getColor(R.color.white));
menu.findItem(Menus.PROCURAR).setVisible(true);
searchCheck = true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case Menus.PROCURAR:
searchCheck = true;
break;
}
return true;
}
private void showResults() {
try {
progressBar = new ProgressBar(getActivity(), null, android.R.attr.progressBarStyle);
LinearLayout.LayoutParams progressBarParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
progressBar.setLayoutParams(progressBarParams);
progressBar.setPadding(6, 6, 6, 6);
footerLinearLayout = new LinearLayout(getActivity());
AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
footerLinearLayout.setGravity(Gravity.CENTER);
footerLinearLayout.setLayoutParams(layoutParams);
footerLinearLayout.addView(progressBar);
lv = (ListView) rootView.findViewById(R.id.listaClientes);
clientes = new ArrayList<ClienteModel>();
ad = new ClientViewAdapter(getActivity(), this, clientes);
lv.setVerticalFadingEdgeEnabled(true);
lv.setVerticalScrollBarEnabled(true);
lv.setAdapter(ad);
} catch (Exception e) {
e.printStackTrace();
}
}
LoadMoreTask:
public class LoadMoreClientTask extends AsyncTask<Integer, Void, Boolean> {
private SearchView.OnQueryTextListener activity;
private ClientViewAdapter adapter;
private List<ClienteModel> cliente = new ArrayList<ClienteModel>();
private ProgressBar progressBar;
private Context context;
public LoadMoreClientTask(ProgressBar progressBar, SearchView.OnQueryTextListener activity, ClientViewAdapter adapter, Context context){
this.progressBar = progressBar;
this.activity = activity;
this.adapter = adapter;
this.context = context;
}
#Override
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected Boolean doInBackground(Integer... parameters) {
int npagina = parameters[0];
cliente= new ArrayList<ClienteModel>();
try {
Repositorio mRepositorio = new Repositorio(context);
List listaDeClientes = mRepositorio.getClientes("", 5, npagina);
cliente = listaDeClientes;
System.out.println("pagina " + npagina);
}catch (Exception e){
e.printStackTrace();
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
adapter.setData(cliente);
}
progressBar.setVisibility(View.INVISIBLE);
}
}
getClientes:
public List<ClienteModel> getClientes( String consulta, Integer limit, Integer pagina) throws SQLException {
int offset = pagina * limit - limit;
System.out.println("OFFSET: "+ offset);
List<ClienteModel> listaDeRegistros = new ArrayList<ClienteModel>();
System.out.println("Consulta: "+ consulta);
if(consulta.isEmpty()) {
query = "SELECT * FROM " + tabelaCLIENTES + " WHERE credencial_id = " + mSessao.getString("id_credencial") + " LIMIT " + offset + ", " + limit;
}else {
query = "SELECT * FROM " + tabelaCLIENTES + " WHERE (credencial_id = " + mSessao.getString("id_credencial") + ") AND (nome LIKE '%"+consulta+"%') LIMIT " + offset + ", " + limit;
}
System.out.println(query);
try {
Cursor mCursor = bd.rawQuery(query, null);
if (mCursor.getCount() > 0) {
if (mCursor.moveToFirst()) {
do {
ClienteModel mClienteModel = new ClienteModel();
mClienteModel.setClientes_id(mCursor.getInt(mCursor.getColumnIndex(ClienteModel.Coluna.CLIENTES_ID)));
mClienteModel.setId_rm(mCursor.getInt(mCursor.getColumnIndex(ClienteModel.Coluna.ID_RM)));
mClienteModel.setCredencial_id(mCursor.getInt(mCursor.getColumnIndex(ClienteModel.Coluna.CREDENCIAL_ID)));
mClienteModel.setNome(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna.NOME)));
mClienteModel.setTipo(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna.TIPO)));
mClienteModel.setInformacao_adicional(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna.INFORMACAO_ADICIONAL)));
mClienteModel.set_criado(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna._CRIADO)));
mClienteModel.set_modificado(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna._MODIFICADO)));
mClienteModel.set_status(mCursor.getString(mCursor.getColumnIndex(ClienteModel.Coluna._STATUS)));
listaDeRegistros.add(mClienteModel);
} while (mCursor.moveToNext());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return listaDeRegistros;
}
It's doing this because you keep adding the footerView for the query changes.
lv.addFooterView(footerLinearLayout);
You should add the footerView one time and keep a reference to it in the Activity and then update the view as needed.