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.
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 know this question has been asked so many times, but none of the solutions answered there seems to solve my problem.
Most of the solutions suggested attaching an adapter (setadapter()) and I have done that. But the problem still seems to persist.
I also checked if my listitems are empty and it isn't.
I have attached the adapter in a function loadUserAccounts().
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_accounts);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Swipe to refresh
swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.userSwipeRefresh);
//Recycler View
recyclerView = (RecyclerView) findViewById(R.id.userRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(userAccountsActivity.this));
listItems = new ArrayList<>();
recyclerViewUserAdapter = new RecyclerViewUserAdapter(listItems, userAccountsActivity.this);
recyclerView.setAdapter(recyclerViewUserAdapter);
//Function to load the users to the recycler view
loadUserAccounts();
/*
* Sets up a SwipeRefreshLayout.OnRefreshListener that is invoked when the user
* performs a swipe-to-refresh gesture.
*/
swipeRefresh.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.i("Swipe_log: ", "onRefresh called from SwipeRefreshLayout");
// This method performs the actual data-refresh operation.
// The method calls setRefreshing(false) when it's finished.
loadUserAccounts();
}
}
);
}
and this is my loadUserAccounts() function:
/**
* Function to load the user account
* into the recycler view from the log database
*/
public void loadUserAccounts(){
String tag_string_req = "req_user_acc";
clear();
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_USER_ACCOUNTS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jArray = new JSONArray(response);
for(int i = jArray.length()-1; i>=0; i--){
JSONObject log = jArray.getJSONObject(i);
String name = log.getString("name");
String cpfNumber = log.getString("cpfNumber");
String type = log.getString("type");
String created_at = log.getString("created_at");
Log.d("Adapter: ", name + cpfNumber + type + created_at);
ListItem_RecyclerView_User item = new ListItem_RecyclerView_User (name, cpfNumber, type, created_at);
listItems.add(item);
}
recyclerViewUserAdapter.updateDataList(responseList);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(error!=null && error.getMessage() !=null){
Log.e(TAG,"User Accounts Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Something went wrong",Toast.LENGTH_LONG).show();
}
}
});
//Adding request to request queue
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
if (swipeRefresh == null)
return;
else {
if (swipeRefresh.isRefreshing()) {
swipeRefresh.setRefreshing(false);
}
}
}
My adapter class RecyclerViewUserAdapter
public class RecyclerViewUserAdapter extends RecyclerView.Adapter<RecyclerViewUserAdapter.ViewHolder> {
private List<ListItem_RecyclerView_User> listItems;
private Context context;
public RecyclerViewUserAdapter(List<ListItem_RecyclerView_User> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
public void updateDataList(List<ListItem_RecyclerView_User> newDatas) {
listItems.clear();
listItems.addAll(newDatas);
notifyDataSetChanged();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.users_recycler_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(RecyclerViewUserAdapter.ViewHolder holder, int position) {
ListItem_RecyclerView_User listItem = listItems.get(position);
holder.txtUserName.setText(listItem.getTxtUserName());
holder.txtUserCpf.setText(listItem.getTxtUserCpf());
holder.txtAccountType.setText(listItem.getTxtAccountType());
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
date = df.parse(listItem.getTxtCreatedDate());
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
String loginTime = sdf.format(date);
holder.txtCreatedDate.setText(loginTime);
} catch (ParseException e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return 0;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView txtUserName;
private TextView txtUserCpf;
private TextView txtAccountType;
private TextView txtCreatedDate;
public ViewHolder(View itemView) {
super(itemView);
txtUserName = (TextView) itemView.findViewById(R.id.txtUserName);
txtUserCpf = (TextView) itemView.findViewById(R.id.txtUserCpf);
txtAccountType = (TextView) itemView.findViewById(R.id.txtAccountType);
txtCreatedDate = (TextView) itemView.findViewById(R.id.txtCreatedDate);
}
}
}
Try this...
modify that getItemCount() to like this.
#Override
public int getItemCount() {
return listItems.size();
}
Try this
Create your adapter with empty list data
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
// your normal code
recyclerView = (RecyclerView) findViewById(R.id.userRecyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(userAccountsActivity.this));
listItems = new ArrayList<>();
// create new adapter
recyclerViewUserAdapter = new RecyclerViewUserAdapter(new ArrayList<>(), userAccountsActivity.this);
recyclerView.setAdapter(recyclerViewUserAdapter);
//your normal code
}
In your response
#Override
public void onResponse(String response) {
try {
List<ListItem_RecyclerView_User> responseList = new ArrayList<>();
JSONArray jArray = new JSONArray(response);
for(int i = jArray.length()-1; i>=0; i--){
JSONObject log = jArray.getJSONObject(i);
String name = log.getString("name");
String cpfNumber = log.getString("cpfNumber");
String type = log.getString("type");
String created_at = log.getString("created_at");
Log.d("Adapter: ", name + cpfNumber + type + created_at);
ListItem_RecyclerView_User item = new ListItem_RecyclerView_User (name, cpfNumber, type, created_at);
responseList.add(item);
}
/*recyclerViewUserAdapter = new RecyclerViewUserAdapter(listItems, userAccountsActivity.this);
recyclerView.setAdapter(recyclerViewUserAdapter);*/
// write method to update your data
recyclerViewUserAdapter.updateDataList(responseList);
} catch (JSONException e) {
e.printStackTrace();
}
}
In your adapter create method
public void updateDataList(List<ListItem_RecyclerView_User> newDatas) {
listItems.clear();
listItems.addAll(newDatas);
notifyDataSetChanged():
}
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
I have jsonParse method inside a onCreateView. I have 3 pages in my application. Every time, when I
open a page data created all of the time and I want to check therefore whether there is already something at the current position. Now, my question is what are recommended way to check a certain data already exists in the ArrayList.
Here is my code :
public class ScheduleSlideFragment extends Fragment {
final static String ARG_PAGE = "page";
private static ViewPager pager;
public static int pageNumber;
public static int PAGE_NUM = ScheduleMainActivity.NUM_PAGES ;
public ArrayList<ScheduleItem> data = new ArrayList<ScheduleItem>();
public int getPageNumber;
private void jsonParseData(int _getPageNumber) {
try {
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this
.getResources().openRawResource(R.raw.program)));
StringBuilder jsonBuilder = new StringBuilder();
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
// Parse Json
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
_getPageNumber = getPageNumber;
JSONObject jsonObject = jsonArray.getJSONObject(_getPageNumber);
String getDate = jsonObject.getString("date");
// data.add(new ScheduleItem(getDate));
JSONArray getFirstArray = new JSONArray(jsonObject.getString("events"));
for (int i = 0; i < getFirstArray.length(); i++) {
JSONObject getJSonObj = (JSONObject)getFirstArray.get(i);
String time = getJSonObj.getString("time");
//Log.e("Time Log",time);
String type = getJSonObj.getString("type");
String title = getJSonObj.getString("title");
int typeId = getJSonObj.getInt("type_id");
data.add(new ScheduleItem(time, title, typeId, getDate));
Log.e("Check Size", String.valueOf(data.size()));
/*
* Get Events
*/
if (typeId == 0) {
JSONArray getEventsArray = new JSONArray(getJSonObj.getString("events"));
for (int j = 0; j < getEventsArray.length(); j++) {
JSONObject getJSonEventobj = (JSONObject)getEventsArray.get(j);
int typeEventId = getJSonEventobj.getInt("type_id");
if (typeEventId == 1) {
String EventInfo = getJSonEventobj.getString("info");
String EventType = getJSonEventobj.getString("type");
String EventTitle = getJSonEventobj.getString("title");
String Eventtime = getJSonEventobj.getString("time");
data.add(new ScheduleItem(Eventtime, EventTitle, EventInfo,
typeEventId, getDate));
} else {
String EventType = getJSonEventobj.getString("type");
String EventTitle = getJSonEventobj.getString("title");
String Eventtime = getJSonEventobj.getString("time");
data.add(new ScheduleItem(Eventtime, EventTitle, typeEventId,
getDate));
}
}
}
}
//Log.e("Check Date", String.valueOf(data.get(_getPageNumber).getDate()));
} catch (Exception e) {
Log.getStackTraceString(e);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.schedule, container, false);
getPageNumber = pageNumber;
/**
* JSON Parsing
*/
checker = getPageNumber + 1;
jsonParseData(getPageNumber);
/**
* Set header date
*/
((TextView)rootView.findViewById(R.id.tvDay)).setText(data.get(pageNumber).getDate().toString());
final ListView list = (ListView)rootView.findViewById(R.id.list);
BinderData bindingData = new BinderData(this.getActivity(), data);
list.setAdapter(bindingData);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
if (data.get(position).getItemType() == 0
|| data.get(position).getItemType() == 3
|| data.get(position).getItemType() == 2)
return;
Intent intent = new Intent(ScheduleSlideFragment.this.getActivity(),
ContentExtended.class);
intent.putExtra("title", data.get(position).getTitle());
intent.putExtra("content", data.get(position).getContent());
startActivity(intent);
}
});
ImageButton ibLeft = (ImageButton)rootView.findViewById(R.id.ibLeft);
if (pageNumber == 0)
ibLeft.setVisibility(View.INVISIBLE);
else
ibLeft.setVisibility(View.VISIBLE);
ibLeft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pager.getCurrentItem() > 0)
pager.setCurrentItem(pager.getCurrentItem() - 1, true);
}
});
ImageButton ibRight = (ImageButton)rootView.findViewById(R.id.ibRight);
if (pageNumber + 1 == PAGE_NUM)
ibRight.setVisibility(View.INVISIBLE);
else
ibRight.setVisibility(View.VISIBLE);
ibRight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pager.getCurrentItem() < PAGE_NUM)
pager.setCurrentItem(pager.getCurrentItem() + 1, true);
}
});
return rootView;
}
public static Fragment create(int position) {
Fragment fragment = new ScheduleSlideFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, position);
fragment.setArguments(args);
return fragment;
}
public static Fragment create(int position, ViewPager _pager) {
pageNumber = position;
pager = _pager;
Fragment fragment = new ScheduleSlideFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, position);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageNumber = getArguments().getInt(ARG_PAGE);
}
}
If the objects inside the ArrayList has the equal methods properly overridden and defined you can use the contains method.
Whenever you need to check if your List contains something, you should use Set instead of List. HashSet for example.
This is my question:
How do I have two spinners "State" and "City" but the city will be empty until the user selects a state first.
I am building my spinners dynamically using json data and you will see in my code below that once the state spinner value is != 0 then I use the item value of the state spinner and do another database call for my cities.
My only error is showing when I create my new ArrayAdapter to hold to the city data. I hate to post all of my code for my activity but not sure where my issue is.
public class SearchActivity extends Activity{
private static final String TAG = "MyApp";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
final Spinner zipspinner = (Spinner) findViewById(R.id.zipspinner);
final Spinner cityspinner = (Spinner) findViewById(R.id.cityspinner);
JSONArray jsonArray;
final JSONArray cityArray;
try {
//GET STATE VALUES FROM DATACALL (DATABASE)
String spinnerContentType = "state";
String spinnerURL = "getStoreState.php";
String spinner_data = DataCall.getJSON(spinnerURL,spinnerContentType);
jsonArray = new JSONArray(spinner_data);
final String[] array_spinner = new String[jsonArray.length()];
for (int i=0; i<jsonArray.length(); i++)
{
String styleValue = jsonArray.getJSONArray(i).getString(0);
array_spinner[i] = styleValue;
}
//ADD STATE VALUES TO SPINNER
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_item,array_spinner);
adapter.setDropDownViewResource(R.layout.state_spinner_layout);
zipspinner.setAdapter(adapter);
zipspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int item = zipspinner.getSelectedItemPosition();
//IF ITEM IN STATE IS SELECTED NOW GET CITIES FROM DATABALL
if(item != 0){
try {
String item_value = array_spinner[item];
String spinnerContentType = "city";
String spinnerURL = "getStoreCity.php?state=" + item_value;
String city_data = DataCall.getJSON(spinnerURL,spinnerContentType);
cityArray = new JSONArray(city_data);
final String[] city_spinner = new String[cityArray.length()];
for (int i=0; i<cityArray.length(); i++)
{
String styleValue = cityArray.getJSONArray(i).getString(0);
city_spinner[i] = styleValue;
}
//THIS IS WHERE MY ISSUE IS TRYING TO ADD THE CITIES TO THEIR SPNNER
ArrayAdapter<String> adapter2 =
new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_item,city_spinner);
adapter2.setDropDownViewResource(R.layout.city_spinner_layout);
cityspinner.setAdapter(adapter2);
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int item = cityspinner.getSelectedItemPosition();
if(item != 0){
String item_value = array_spinner[item];
String nameContentType = "name";
String shopURL = "getStoreList.php?city=" + item_value;
String name_data = DataCall.getJSON(shopURL,nameContentType);
Bundle bundle = new Bundle();
bundle.putString("shopData", name_data);
Log.v(TAG,name_data);
/** Intent myIntent = new Intent(SearchActivity.this, ShowRestaurant.class);
myIntent.putExtras(bundle);
startActivityForResult(myIntent, 0); */
}
else {
// finish();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
// finish();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Set all your Adapters and String arrays first and then just call adapter.notifyDatasetChanged() while you got the data for city. something like this:
String city_values[] = new String[]{"Please select a state."};
ArrayAdapter<String> adapter2 = new ArrayAdapter<String> (this,android.R.layout.simple_spinner_item, city_spinner);
adapter2.setDropDownViewResource(R.layout.city_spinner_layout);
cityspinner.setAdapter(adapter2);
for the zipspinner implement a OnItemSelectedListener.
zipspinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent,View view, int pos, long id) {
String value = state_values[pos];
// now get your city list against value.
city_values = yourWayOfGettingData(value);
adapter2.notifyDatasetChanged();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});