I'm trying to change a few parts in my app. I can't figure out how to set up my app so each tab changes the data in my listview. Any help appreciated.
My tab setup class:
public class WorkoutDaysActivity extends BaseActivity {
ListView mListView = new ListView(this);
ArrayList < CustomObject > w29w1m;
CustomListViewAdapter mCustomListViewAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout_days);
mToolBar = activateToolbar();
setUpNavigationDrawer();
w29w1m.add(new CustomObject("Squat", "65%", "6", "150", false));
final ArrayList < CustomObject > w29w1w = new ArrayList < CustomObject > ();
w29w1w.add(new CustomObject("Dead", "65%", "6", "150", false));
final ArrayList < CustomObject > w29w1f = new ArrayList < CustomObject > ();
w29w1f.add(new CustomObject("Bench", "65%", "6", "150", false));
TabHost tabHost = (TabHost) findViewById(R.id.TabHost1);
tabHost.setup();
tabHost.addTab(tabHost.newTabSpec("1").setIndicator("Monday").setContent(objects));
tabHost.addTab(tabHost.newTabSpec("1").setIndicator("Wednesday").setContent(objects));
tabHost.addTab(tabHost.newTabSpec("1").setIndicator("Friday").setContent(objects));
}
private TabHost.OnTabChangeListener mOnTabChangeListener = new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
if (tabId.equalsIgnoreCase("1"))
mListView.setAdapter(mCustomListViewAdapter, w29w1m);
}
};
private final TabHost.TabContentFactory objects = new TabHost.TabContentFactory() {
#Override
public View createTabContent(String tag) {
return mListView;
}
};
}
customObject class:
public class CustomObject implements Serializable {
private String exercise;
private String percent;
private String reps;
private String weight;
private boolean check1;
public CustomObject(String exercise, String percent, String reps, String weight, boolean check1) {
this.exercise = exercise;
this.percent = percent;
this.reps = reps;
this.weight = weight;
this.check1 = check1;
}
public String getExercise() {
return exercise;
}
public String getPercent() {
return percent;
}
public String getReps() {
return reps;
}
public String getWeight() {
return weight;
}
Adapter class
public class CustomListViewAdapter extends BaseAdapter {
private LayoutInflater inflater;
public ArrayList < CustomObject > objects;
boolean[] checkBoxState;
private CustomObject[] dataToBePopulated;
private class ViewHolder {
TextView txtExercise;
TextView txtPercent;
TextView txtReps;
TextView txtWeight;
CheckBox check1;
}
public void addAdapterItem(CustomObject item) {
objects.add(item);
}
public CustomListViewAdapter(Context context, ArrayList < CustomObject > objects){
inflater = LayoutInflater.from(context);
this.objects = objects;
checkBoxState = new boolean[objects.size()];
}
public int getCount() {
return dataToBePopulated != null ? dataToBePopulated.length : 0;
}
public CustomObject getItem(int position) {
return objects.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.workout_item, null);
holder.txtExercise = (TextView) convertView.findViewById(R.id.txtExercise);
holder.txtPercent = (TextView) convertView.findViewById(R.id.txtPercentage);
holder.txtReps = (TextView) convertView.findViewById(R.id.txtReps);
holder.txtWeight = (TextView) convertView.findViewById(R.id.txtWeight);
holder.check1 = (CheckBox) convertView.findViewById(R.id.check1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtExercise.setText(objects.get(position).getExercise());
holder.txtPercent.setText(objects.get(position).getPercent());
holder.txtReps.setText(objects.get(position).getReps());
holder.txtWeight.setText(objects.get(position).getWeight());
holder.check1.setChecked(checkBoxState[position]);
holder.check1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkBoxState[position] = true;
} else {
checkBoxState[position] = false;
}
}
});
return convertView;
}
}
The problem is I don't know how to set up my adapter to show the custom array lists Im making (w29w1m for example). Any help greatly appreciated! thanks!
If you're just going to change the data inside the adapter, try changing the list that you've set on the adapter. Then call notifyDataSetChanged() on the adapter. For example, if you've instantiated the adapter like LVAdapter lvAdapter = new LVAdapter(context, list); (or whatever parameter you use in your adapter), just change list to what you want the ListView to contain, then call lvAdapter.notifyDataSetChanged();.
But if you'd also change the adapter, try to set another adapter to the listview every time the tab is changed.
Also, I suggest making the tabSpec ids unique for each one.
Related
I need to display name, phoneNumber and accountNumber in EditText in the class ConsumerdescAndEdit, so how do pass these values when OnItemClickListener is executed?
ShowAll.java:
I have the ListView that inflated from CustomAdapter.
Intent intent = new Intent(ShowAll.this,ConsumerDescAndEdit.class);
startActivity(intent);
CustomAdapter.java:
public class CustomAdapter extends BaseAdapter {
Context mContext;
TextView nameView;
TextView phoneNumberView;
TextView accountView;
String name;
String phoneNumber;
String accountNumber;
ArrayList<Consumer> objects;
public CustomAdapter(Context context, int resource, ArrayList<Consumer> objects){
this.objects = objects;
this.mContext = context;
}
public CustomAdapter(){
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Consumer consumer = (Consumer) getItem(position);
// Values to be displayed.
name = consumer.getName();
phoneNumber = consumer.getPhoneNumber();
accountNumber = consumer.getAccountNumber();
LayoutInflater inflater = LayoutInflater.from(mContext); // generate an inflater using context.
convertView = inflater.inflate(R.layout.details_layout,null); // inflate details_layout and store it in convertView.
nameView = convertView.findViewById(R.id.nameView);
phoneNumberView = convertView.findViewById(R.id.phoneNumberView);
accountView = convertView.findViewById(R.id.accountView);
nameView.setText(name);
phoneNumberView.setText(phoneNumber);
accountView.setText(accountNumber);
return convertView;
}
}
ConsumerDescAndEdit.java (where do I need to use variables):
public class ConsumerDescAndEdit extends AppCompatActivity {
Button updateButton;
EditText nameEditTextVar;
EditText phoneEditTextVar;
EditText accountEditTextVar;
// Variables to store user inputted data.
String nameEdit;
String phoneEdit;
String accountEdit;
DatabaseHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consumer_desc_and_edit);
dbHelper = new DatabaseHelper(this);
updateButton = findViewById(R.id.updateButton);
nameEditTextVar = findViewById(R.id.nameEditScreen);
phoneEditTextVar = findViewById(R.id.phoneNumberEditScreen);
accountEditTextVar = findViewById(R.id.accountNumberEditScreen);
String s_intent = getIntent().getStringExtra("EXTRA_SESSION_ID");
nameEditTextVar.setText(s_intent);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nameEdit = nameEditTextVar.getText().toString();
phoneEdit = phoneEditTextVar.getText().toString();
accountEdit = accountEditTextVar.getText().toString();
if (nameEdit.isEmpty() || phoneEdit.isEmpty() || accountEdit.isEmpty()) {
Toast.makeText(ConsumerDescAndEdit.this, "Data Insufficient", Toast.LENGTH_SHORT).show();
} else {
boolean b = dbHelper.updateData(nameEdit, phoneEdit, accountEdit);
if (b)
Toast.makeText(ConsumerDescAndEdit.this, "Data updated", Toast.LENGTH_SHORT).show();
else
Toast.makeText(ConsumerDescAndEdit.this, "Could not update data", Toast.LENGTH_SHORT).show();
}
}
});
}
}
When you create the Intent for the edit Activity, add the data from the selected item as "extras" to the Intent, like this:
Intent intent = new Intent(ShowAll.this,ConsumerDescAndEdit.class);
intent.putExtra("name", name);
intent.putExtra("phone", phone);
intent.putExtra("account", account);
startActivity(intent);
In the edit Activity, extract the data from the Intent like this:
String name = intent.getStringExtra("name");
String phone = intent.getStringExtra("phone");
String account = intent.getStringExtra("account");
Try below code
public class CustomAdapter extends BaseAdapter {
Context mContext;
TextView nameView;
TextView phoneNumberView;
TextView accountView;
String name;
String phoneNumber;
String accountNumber;
ArrayList<Consumer> objects;
private ItemClickListener itemClickListener;
public interface ItemClickListener {
void onItemClick(Consumer consumer);
}
public CustomAdapter(Context context, int resource, ArrayList<Consumer> objects, ItemClickListener itemClickListener) {
this.objects = objects;
this.mContext = context;
this.itemClickListener = itemClickListener;
}
public CustomAdapter() {
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Consumer consumer = (Consumer) getItem(position);
// Values to be displayed.
name = consumer.getName();
phoneNumber = consumer.getPhoneNumber();
accountNumber = consumer.getAccountNumber();
LayoutInflater inflater = LayoutInflater.from(mContext); // generate an inflater using context.
convertView = inflater.inflate(R.layout.details_layout, null); // inflate details_layout and store it in convertView.
nameView = convertView.findViewById(R.id.nameView);
phoneNumberView = convertView.findViewById(R.id.phoneNumberView);
accountView = convertView.findViewById(R.id.accountView);
nameView.setText(name);
phoneNumberView.setText(phoneNumber);
accountView.setText(accountNumber);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (itemClickListener != null) {
itemClickListener.onItemClick(consumer);
}
}
});
return convertView;
}
}
In Activity do following
public class ConsumerActivity extends AppCompatActivity implements CustomAdapter.ItemClickListener {
CustomAdapter adapter;
ArrayList<Consumer> objects;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consumer);
adapter = new CustomAdapter(this, objects, this);
}
#Override
public void onItemClick(Consumer consumer) {
Intent intent = new Intent(this, CustomerEdit.class);
intent.putExtra("Consumer", consumer);
startActivity(intent);
}
}
i have 2 arrays productname and price. my each row in listview contains productname,price and an image button remove. when i click remove button,the selected productname and price should be removed from my array as well as from my listview. Please guide me doing this,is very important for me. If there is another way of doing this plz let me know.i m student only!
this is my CartActivity
public class CartActivity extends Activity implements View.OnClickListener {
CartAdapter contactAdapter;
ListView listView;
public String productname[]=new String[10];
public String price[]=new String[10];
int i=0,m;
CartActivity(String scanContent){
this.content = scanContent;
}
public CartActivity() {}
String product,Price;
String pri,prod;
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
listView = (ListView) findViewById(R.id.cart_list_view);
contactAdapter = new CartAdapter(this,R.layout.activity_cart_list_view);
listView.setAdapter(contactAdapter);
intent = getIntent();
productname = intent.getStringArrayExtra("productname");
price = intent.getStringArrayExtra("price");
for(int j=0;j<price.length;j++) {
product = productname[j];
Price = price[j];
if (Price != null || product != null) {
Cart contacts = new Cart(product, Price);
contactAdapter.add(contacts);
}
}
}
this is my CartAdapter
public class CartAdapter extends ArrayAdapter {
List list = new ArrayList();
int ind,x=0;
public CartAdapter(CartActivity context, int resource) {
super(context, resource);
}
public void add(Cart object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
ContactHolder contactHolder;
if(row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.activity_cart_list_view,parent,false);
contactHolder = new ContactHolder();
contactHolder.tx_name =(TextView) row.findViewById(R.id.product_name);
contactHolder.tx_price =(TextView) row.findViewById(R.id.price);
contactHolder.cancelButton = (ImageButton) row.findViewById(R.id.cancel_button);
row.setTag(contactHolder);
}
else
{
contactHolder = (ContactHolder)row.getTag();
}
cancelButton.setTag(position);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer index = (Integer) view.getTag();
list.remove(index.intValue());
notifyDataSetChanged();
}
});
Cart contacts = (Cart) this.getItem(position);
contactHolder.tx_name.setText(contacts.getItemname());
contactHolder.tx_price.setText(contacts.getPrice());
return row;
}
static class ContactHolder
{
TextView tx_name,tx_price;
ImageButton cancelButton;
}
}
this is my Cart
public class Cart {
private String itemname,price;
public Cart(String itemname,String price) {
this.setItemname(itemname);
this.setPrice(price);
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public void setPrice(String price) {
this.price = price;
}
public String getItemname() {
return itemname;
}
public String getPrice() {
return price;
}
}
my each row in a listview contains this
Just do this,
in your adapter class,
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
list.remove(position); //position is getView position
// above line will remove from arraylist
notifyDataSetChanged(); //this line reflects change in listview
}
});
To remove from Activity class,
better create an ArrayList first.
ArrayList<Cart> cardList = new ArrayList<Cart>();
add into arrayList,
if (Price != null || product != null) {
Cart contacts = new Cart(product, Price);
cardList.add(contacts);
contactAdapter.add(contacts); // this line should be removed if you work with arrayList
}
now create a method to remove from ActivityCard arrayList,
//call this method from cancelimage click in adapter class
public void removeFromList(int position){
cardList.remove(position); //this will remove from activity arraylist
}
At the end calculate your bill from existing cartList data.
*** You can also create adapter class object with cardList just changing your constructor. If you do this then just call removeFromList on cancelimage click and put,
adapter.notifyDataSetChanged();
after
cardList.remove(position);
it will refresh your listview also.
I'm developing an android app which has a custom listview with a checkbox. I want to pass all the checked items from one activity to another. how should I pass them? and where should I manage the checkbox (to get all the checked items) in the custom adapter or the activity?
Note: I retrieve all the data from my server using json response.
Here's my Model :
public class Groups {
public String name;
public boolean selected= false;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public Groups() {
}
}
My Adapter:
public class AdapterMainActivity extends BaseAdapter{
Activity activity;
private LayoutInflater inflater;
List<Groups> groupsList;
public AdapterMainActivity(Activity activity, List<Groups> groupses) {
this.activity = activity;
this.groupsList = groupses;
}
#Override
public int getCount() {
return groupsList.size();
}
#Override
public Object getItem(int position) {
return groupsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_list, null);
TextView name = (TextView) convertView.findViewById(R.id.textViewName);
final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
final Groups groups = groupsList.get(position);
name.setText(groupsList.get(position).getName());
checkBox.setChecked(groups.selected);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
groups.selected = isChecked;
MainActivity.getInstance().updateArrayList(groupsList);
}
});
}
return convertView;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
ListView listViewGroups;
Button buttonSentToActivity;
List<Groups> groupsList;
List<Groups> resultGroupList;
ArrayList<Boolean> areChecked;
List<String> finalArray;
private AdapterMainActivity adapterMainActivity;
static MainActivity yourActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourActivity = this;
groupsList= new ArrayList<Groups>();
resultGroupList= new ArrayList<Groups>();
ReadGroup(37);
adapterMainActivity = new AdapterMainActivity(this, groupsList);
listViewGroups = (ListView) findViewById(R.id.listViewGroups);
listViewGroups.setAdapter(adapterMainActivity);
buttonSentToActivity = (Button) findViewById(R.id.buttonSendTo2Activity);
buttonSentToActivity.setOnClickListener(buttonSentToActivityListener);
Log.e("Group list size ", String.valueOf(groupsList.size()));
finalArray = new ArrayList<>();
for (int i = 0; i < resultGroupList.size(); i++) {
if (resultGroupList.get(i).selected) {
finalArray.add(resultGroupList.get(i).getName());
Log.e("final array size", String.valueOf(finalArray.size()));
}
}
}
public void ReadGroup(long cid) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray readArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < readArray.length(); i++) {
Log.e("i is: ", String.valueOf(i));
JSONObject jssonRow = readArray.getJSONObject(i);
String groupName = jssonRow.getString("name");
Groups groups = new Groups();
groups.setName(groupName);
Log.e("NAME is: ", groupName);
groupsList.add(groups);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapterMainActivity.notifyDataSetChanged();
}
};
Log.e("Client id is: ", String.valueOf(cid));
ReadGroupRequesr readGroupRequest = new ReadGroupRequesr(cid, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(readGroupRequest);
Log.e("out of the loop", "");
}
public static MainActivity getInstance() {
return yourActivity;
}
public void updateArrayList(List<Groups> arrayList) {
this.resultGroupList = arrayList;
}
View.OnClickListener buttonSentToActivityListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
//Bundle b= new Bundle();
//b.putStringArrayList("arrayList", (ArrayList<String>) finalArray);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putStringArrayListExtra("arrayList", (ArrayList<String>) finalArray);
//intent.putExtras(b);
Log.e("final array size", String.valueOf(finalArray.size()));
startActivity(intent);
}
};
}
At the very first, manage your checkboxes :
In your activity class add a boolean array or arraylist having size same as your list array size and initialize it with all value as false initially :
String[] titlesArray;
ArrayList<Boolean> arrChecked;
// initialize arrChecked boolean array and add checkbox value as false initially for each item of listview
arrChecked = new ArrayList<Boolean>();
for (int i = 0; i < titles.size(); i++) {
arrChecked.add(false);
}
Now replace your adapter class with this :
class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();
ArrayList<Boolean> arrChecked;
VivzAdapter(Context context, String[] titles, int[] images, String[] description, ArrayList<Boolean> arrChecked) {
super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
this.arrChecked = arrChecked;
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView1);
myTitle = (TextView) v.findViewById(R.id.textView1);
myDescription = (TextView) v.findViewById(R.id.textView2);
box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.Âștime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
//set position as id
holder.box.setId(position);
//set onClickListener of checkbox rather than onCheckedChangeListener
holder.box.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (arrChecked.get(id)) {
//if checked, make it unchecked
arrChecked.set(id, false);
} else {
//if unchecked, make it checked
arrChecked.set(id, true);
}
}
});
//set the value of each checkbox from arrChecked boolean array
holder.box.setChecked(arrChecked.get(position));
return row;
}
}
After that, implement click listener of send button say btnSend button (I am considering that you are sending your data from one activity to another activity on click of send button) :
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> arrTempList = new ArrayList();
for(int i=0; i<titles.size(); i++){
if(arrChecked.get(i) == true){
arrTempList.add(titles[i]);
}
}
// here you can send your arrTempList which is having checked items only
}
});
Here's the solution for this Question:
My adapter:
public class ChooseContactsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
public ArrayList<Contacts> contactsList;
public CheckBox checkBoxAdapter;
public ChooseContactsAdapter(Activity activity, ArrayList<Contacts> group) {
this.activity = activity;
this.contactsList = group;
}
#Override
public int getCount() {
return contactsList.size();
}
#Override
public Object getItem(int position) {
return contactsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_choose_contacts_sms,
null);
final TextView fNAme = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactFName);
TextView LName = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactLName);
checkBoxAdapter = (CheckBox) convertView.findViewById(R.id.checkBoxSelectContact);
checkBoxAdapter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
Contacts contacts = (Contacts) cb.getTag();
contacts.setSelected(cb.isChecked());
Toast.makeText(activity.getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
}
});
final Contacts contacts = contactsList.get(position);
fNAme.setText(contacts.getContactFName());
LName.setText(contacts.getContactLName());
checkBoxAdapter.setChecked(contacts.isSelected());
checkBoxAdapter.setTag(contacts);
}
return convertView;
}
}
In my activity I have button to go from 1 activity to the 2 activity:
private View.OnClickListener buttonSubmitGroupListener =new View.OnClickListener() {
#Override
public void onClick(View view) {
List <Integer> contactsIDArray= new ArrayList<Integer>();
List<Contacts> arrayOfContacts= chooseContactsAdapter.contactsList;
for(int i=0; i< arrayOfContacts.size(); i++){
Contacts contacts= arrayOfContacts.get(i);
if(contacts.isSelected()==true){
contactsIDArray.add(contacts.getContactID());
}
}
for (int i = 0; i < contactsIDArray.size(); i++) {
Log.e("Id Array size ", String.valueOf(contactsIDArray.size()));
Log.e("Selected id ", String.valueOf(contactsIDArray.get(i)));
}
intent = new Intent(getApplicationContext(), SendSMSActivity.class);
Bundle b = new Bundle();
b.putIntegerArrayList("checkedContacts", (ArrayList<Integer>) contactsIDArray);
intent.putExtras(b);
startActivity(intent);
}
};
Second Activity add this code:
Bundle b = getIntent().getExtras();
List<Integer> result = new ArrayList<Integer>();
result = b.getIntegerArrayList("checkedContacts");
How can I pass the user input number from EditText in android and set it on the 2nd number in for statement inside my _createListView()?
public class MainActivity extends Activity {
private ListView _listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
Intent intent = getIntent();
int int_text = intent.getIntExtra("name", 100);
this._listView = (ListView) this.findViewById(R.id.listview);
this._createListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void _createListView() {
List<RowItem> rowItems = new ArrayList<RowItem>();
for (int i = 1; i <= 100 ; i++) {
String indexAsString = String.valueOf(i);
if (i % 3 == 0 && i % 5 == 0) {
rowItems.add(new RowItem(indexAsString, "FizzBuzz"));
} else if (i % 3 == 0) {
rowItems.add(new RowItem(indexAsString, "Fizz"));
} else if (i % 5 == 0) {
rowItems.add(new RowItem(indexAsString, "Buzz"));
} else {
rowItems.add(new RowItem(indexAsString, indexAsString));
}
}
RowItemArrayAdapter arrayAdapter = new RowItemArrayAdapter(this,
R.layout.activity_main_list_row, rowItems);
this._listView.setAdapter(arrayAdapter);
}
private static class RowItem {
private String _index;
private String _value;
public RowItem(String index, String value) {
this._index = index;
this._value = value;
}
public String getIndex() {
return this._index;
}
public String getValue() {
return this._value;
}
}
private static class ViewHolder {
public TextView indexTextView;
public TextView valueTextView;
}
private static class RowItemArrayAdapter extends ArrayAdapter<RowItem> {
private LayoutInflater _layoutInflater;
private int _textViewResourceId;
public RowItemArrayAdapter(Context context, int resource, List<RowItem> objects) {
super(context, resource, resource, objects);
this._layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this._textViewResourceId = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final RowItem rowItem = (RowItem) this.getItem(position);
ViewHolder viewHolder;
if (null == convertView) {
convertView = this._layoutInflater.inflate(this._textViewResourceId, null);
viewHolder = new ViewHolder();
viewHolder.indexTextView = (TextView) convertView.findViewById(R.id.index);
viewHolder.valueTextView = (TextView) convertView.findViewById(R.id.value);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.indexTextView.setText(rowItem.getIndex());
viewHolder.valueTextView.setText(rowItem.getValue());
return convertView;
}
}
}
Get the value in a string and call it whereever you want orelse if you want to store it somewhere use sharedpreference.
Store values with sharedpreference :
SharedPreference mypref = getActivity().getSharedPreferences("name_key", Context.MODE_PRIVATE);
SharedPreferences.Editor editor= mypref.edit();
editor.putString("name_key",name_string);
editor.apply();
To retrieve it from anywhere in your program:
SharedPreference mypref = getActivity().getSharedPreferences("name_key", Context.MODE_PRIVATE);
String av = mypref.getString("name","");
im new to android and java programming. Im having trouble getting my custom layout (currently with only one textview in it to work with my code. I have followed many tutorials and look and many examples but still Im getting confused as to how I would integrate it with my existing code.
Any help would be appreciated.
Here is my code:
public class checkListActivity extends MainActivity {
static String filename = "checkList";
String currentList;
SharedPreferences checkListData;
SharedPreferences.Editor checkListEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.checklist);
Button bAddItem = (Button) findViewById(R.id.bAddItem);
final EditText etItemName = (EditText) findViewById(R.id.etItemName);
final TextView tvTitle = (TextView) findViewById(R.id.tvTitle);
final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckLists);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String selectedItem = extras.getString("selectedItem");
// get the value based on the key
currentList = selectedItem;
}
tvTitle.setText(currentList);
checkListData = getSharedPreferences(filename, 0);
updateListView();
// Button Click Listener
bAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String checkListStringData = etItemName.getText().toString();
checkListData = getSharedPreferences(filename, 0);
SharedPreferences.Editor checkListEditor = checkListData.edit();
checkListEditor.putString(currentList + "ItemName",
checkListStringData);
checkListEditor.commit();
String checkListDataReturned = checkListData.getString(
currentList + "ItemName", currentList);
tvTitle.setText(checkListDataReturned);
updateListView();
etItemName.setText("");
};
});
}
private void updateListView() {
final ListView lvCheckList = (ListView) findViewById(R.id.lvCheckList);
Map<String, ?> keys = checkListData.getAll();
ArrayList<String> checkListStrings = new ArrayList<String>();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
if (entry.getValue() instanceof String) {
if (entry.getKey().equals(currentList + "ItemName")) {
checkListStrings.add((String) entry.getValue());
}
}
ArrayAdapter<String> checkListArrayAdapter = new ArrayAdapter<String>(
this, R.layout.single_listview_item);
lvCheckList.setAdapter(checkListArrayAdapter);
}
}
}
first create this custom adapter class...
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public Context con;
public String[] sms;
public EfficientAdapter(Context context,String[] rssFeed) {
mInflater = LayoutInflater.from(context);
this.con=context;
this.sms=rssFeed;
}
public int getCount() {
return sms.length;
}
public Object getItem(int position) {
return sms[position];
}
public long getItemId(int position) {
return position;
}
#SuppressLint({ "SdCardPath", "InflateParams", "ResourceAsColor" })
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder();
holder.text2 = (TextView) convertView.findViewById(R.id.text_list_f);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text2.setText(sms[position]);
}
return convertView;
}
}
static class ViewHolder {
TextView text2;
}
then use it in your activity ...
list.setAdapter(new EfficientAdapter(this, your array));