Checking Checkbox When Listview Item is Selected - android

So essentially I have a listview that contains a custom adapter that deals with formatting the listview. The custom view used by the adapter contains a checkbox that I want to be checked with the check locked when the listview item is selected. After much searching and various attempts at accomplishing this I have not been successful. Any ideas as to how to accomplish this would be greatly appreciated.
Here is the code for my main class:
public class AbWorkout extends Activity {
Button back;
ListView workoutExerciseList;
WorkoutTracker tracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ab_workout);
/**
* The database used to pull all exercises for this workout routine
*/
final DatabaseHandler db = new DatabaseHandler(this);
final SQLiteDatabase database = db.getReadableDatabase();
final Context context = this;
/**
* Get all exercises from Triceps and Chest workout and put in arraylist
*/
workoutExerciseList = (ListView)findViewById(R.id.listView10);
final List<String> arrayWorkoutExercises = new ArrayList<String>();
final ArrayAdapter<String> exListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, arrayWorkoutExercises);
workoutExerciseList.setAdapter(exListAdapter);
//Holds all the available exercises
final List<WorkoutTracker> exerciseList = db.getRepetitionWorkoutRoutine(context, database, "Abs");
/**
* Populates the listView with each exercise for this workout routine. This includes the
* each exercise name, the number of repetitions, the weight of the exercise, and any
* comments included.
*/
List<AbWorkout.RepListViewItem> repProgressList = new ArrayList<>();
for(int i = 0; i<exerciseList.size(); i++) {
final int j = i;
repProgressList.add(new AbWorkout.RepListViewItem()
{{
REPETITIONS = exerciseList.get(j).getReps();
WEIGHT = exerciseList.get(j).getWeight();
COMMENT = exerciseList.get(j).getComment();
EXERCISE_NAME = exerciseList.get(j).getExerciseName();
}});
}
final AbViewAdapter adapter = new AbViewAdapter(this, repProgressList);
workoutExerciseList.setAdapter(adapter);
CheckBox checkBox = (CheckBox)findViewById(R.id.CheckBox);
workoutExerciseList.setItemChecked(ListView.CHOICE_MODE_MULTIPLE, true);
/*
Upon selection of an exercise, it is highlighted and its name, date,
and number of reps is stored in repetition progress table
*/
workoutExerciseList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
CheckBox check = (CheckBox) findViewById(R.id.CheckBox);
//check.setChecked(true);
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yy");
//Get today's date formatted like this: dd-MM-yy
String exDate = format.format(calendar.getTime());
//When exercise is selected, change the color and make it unselectable.
myAdapter.getChildAt(myItemInt).setBackgroundColor(Color.MAGENTA);
myAdapter.getChildAt(myItemInt).setEnabled(false);
myAdapter.getChildAt(myItemInt).setClickable(false);
myView.setClickable(true);
tracker = exerciseList.get(myItemInt);
db.addNewRepProgress(new WorkoutTracker(tracker.getExerciseName(), tracker.getReps(), tracker.getWeight(), tracker.getComment(), exDate), context, database);
Toast.makeText(context.getApplicationContext(), "Workout Progress was successfully saved.", Toast.LENGTH_LONG).show();
}
});
back = (Button)findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#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_ab_workout, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class RepListViewItem
{
public int REPETITIONS;
public double WEIGHT;
public String COMMENT;
public String EXERCISE_NAME;
public String DATE;
}
}
And here is the code for my adapter class:
public class AbViewAdapter extends BaseAdapter
{
LayoutInflater inflater;
List<AbWorkout.RepListViewItem> items;
int pos = 0;
public AbViewAdapter(Activity context, List<AbWorkout.RepListViewItem> items) {
super();
this.items = items;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
AbWorkout.RepListViewItem item = items.get(position);
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.rep_item_row, null);
TextView exerciseName = (TextView)vi.findViewById(R.id.FullProgress);
TextView exerciseReps = (TextView)vi.findViewById(R.id.Time);
TextView exerciseComment = (TextView)vi.findViewById(R.id.Comment);
TextView exerciseWeight = (TextView)vi.findViewById(R.id.Distance);
CheckBox check = (CheckBox)vi.findViewById(R.id.CheckBox);
exerciseName.setText(item.EXERCISE_NAME);
exerciseReps.setText(String.valueOf(item.REPETITIONS));
exerciseComment.setText(item.COMMENT);
exerciseWeight.setText(String.valueOf(item.WEIGHT));
pos = position;
return vi;
}
}

because when you scroll your listview, the item in A will be destroyed. When scroll up, the item in A will be re-created.
So the CheckBox is re-create too, you need to store item when to restore this current state when scroll up. Let see ViewHolder

In your AbViewAdapter.getView(), add an OnClickListener
Then, in the OnClickListener, toggle the checkbox state with:
check.setChecked(!isChecked())
Full answer here: Android listview with check boxes?
Full tutorial here: http://www.mysamplecode.com/2012/07/android-listview-checkbox-example.html

Related

How do I add items to a listView (for duplicates increase quantity) and view in following activity?

I have an a gridView that has items, each item has a name and quantity. When I click the item in the gridView, I would like to add the item and the quantity to a dynamic list view that is in the same activity. If I click on the item a several times, the items quantity in the dynamic listView should be increased (no duplicate items are allowed.) This is my current gridView, I have removed the code that adds and a previous listView that failed and I am having it just toast for now:
public class GridviewAdapter extends BaseAdapter
{
private ArrayList<String> listItem;
private ArrayList<Integer> listPicture;
private Activity activity;
public GridviewAdapter(Activity activity, ArrayList<String> listItem, ArrayList<Integer> listPicture) {
super();
this.listItem = listItem;
this.listPicture = listPicture;
this.activity = activity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listItem.size();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listItem.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public ImageView itemPicture;
public TextView itemName;
public TextView itemPrice;
public TextView itemStock;
public TextView itemAvailability;
}
#Override
public View getView(int position, View convertView, ViewGroup
parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.item_grid_row,
null);
view.itemName = (TextView)
convertView.findViewById(R.id.itemName);
view.itemPrice = (TextView)
convertView.findViewById(R.id.itemPrice);
view.itemStock = (TextView)
convertView.findViewById(R.id.itemStock);
view.itemAvailability = (TextView)
convertView.findViewById(R.id.itemAvailability);
view.itemPicture = (ImageView)
convertView.findViewById(R.id.itemPicture);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.itemName.setText(listItem.get(position));
// view.itemPicture.setImageDrawable(listItem.get(position));
return convertView;
}
}
this is the code for the checkout fragment where the gridView is clicked.
public class CheckoutFragment extends Fragment {
private CheckoutViewModel checkoutViewModel;
private EditText editText1;
private GridviewAdapter mAdapter;
private ArrayList<String> listItem;
private ArrayList<Integer> listPicture;
private GridView gridView;
DBHelper db;
LinearLayout layout_total, layout_grid;
private Button sum;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle
savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_checkout,
container, false);
db = new DBHelper(getActivity());
Display display =
getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
editText1 = (EditText)root.findViewById(R.id.editText1);
editText1.setHeight(height/12);
editText1.setShowSoftInputOnFocus(false);
editText1.setFocusable(false);
editText1.setTextColor(Color.parseColor("#FFFFFF"));
editText1.setHintTextColor(Color.parseColor("#FFFFFF"));
editText1.getBackground().setColorFilter(Color.parseColor("#008577"),
PorterDuff.Mode.SRC_ATOP);
editText1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cart = new Intent(getActivity(),
CartActivity.class);
startActivity(cart);
}
});
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(getActivity(),db.getAll(),
listPicture);
// Set custom adapter to gridview
gridView = (GridView)root.findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new
AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int
position,
long arg3) {
//this is where the grid is clicked and items added to dynamic listView
Toast.makeText(getActivity(),
mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
return root;
}
public void prepareList() {
// listItem = new ArrayList<String>();
db = new DBHelper(getActivity());
List<Item> listItem = new ArrayList<>();
listItem = db.getAllItems(db.ITEMS_TABLE_NAME);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case R.id.action_add_customer:
//startActivity(getActivity(),
NewCustomerActivity.class);
Intent newCustomer = new Intent(getActivity(),
NewCustomerActivity.class);
startActivity(newCustomer);
return true;
/* case R.id.action_add_customer:
return true;*/
default:
return super.onOptionsItemSelected(item);
}
}
}
You need to explain the situation a bit better. For now i assume your problem is that the items are duplicating the second list instead of appending the count. For this there is no
one line solution. What you need to do is once an item is selected in the grid, search if it exists in the second list. In that case update the quantity, otherwise add it to the list. Since your second list is based on a Table , you have to execute 2 queries. One to identify if the item already exists (Select Query) and other to change the value (Insert or Update Query). If i misunderstood please correct me so that i can help you better.
Why don't you return the model class in your GridView getItem(..) method instead of 'String' it should work like this
public class GridviewAdapter extends BaseAdapter
{
ArrayList<GridModel> gridItems;
//Constructor
public GridviewAdapter(Activity activity, ArrayList<GridModel> gridItems) {
super();
this.gridItems = gridItems;
this.activity = activity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return griditems.size();
}
#Override
public GridModel getItem(int position) {
// TODO Auto-generated method stub
return gridItems.get(position);
}
//...add your getView...
}
//GridModel Should be Like So..
class GridModel {
public String itemPicture;
public String itemName;
public String itemPrice;
public String itemStock;
public String itemAvailability;
//or use private variables with getter-setter methods
}

Refresh Fargment from adapter

I know this question has been around, but trying solutions proposed in SO threads weren't helpful!
I Have an activity (Favorites) with 3 fragment (represent categories, Video/figures/other) ..in each fragment there is a list of favorites following the category ..
my problem is ..when i delete an item from list of favorite ..it get deleted from database but the listview don't get refresh instantely! ..i have to move between fragments for that to happen ..
i tried:
1. notifyDataSetChanged(); //do nothing
2. `refreshEvents(listfavorite);` // after the delete button onclick with refresh events=:
public void refreshEvents(final List<Data> events)
{
this.listfavorite.clear();
this.listfavorite.addAll(events);
notifyDataSetChanged();
The result of 2nd method: the list is cleared instantely but don't get repopulated again!
3.
//after on delete on click
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//listfavorite.addAll(events);
notifyDataSetChanged(); }
}, 1000);
This is my Fragment Adapter
public class FragmentAdapter extends BaseAdapter {
private List<Data> listfavorite;
Context context;
String name, packagename, id, section;
Long _id;
private DBManager dbManager;
boolean isFavourite;
private LayoutInflater mInflater;
public FragmentAdapter(Context FragmentOther,List<Data> resultsFavorite){
this.listfavorite = resultsFavorite;
this.context=FragmentOther;
mInflater = LayoutInflater.from(FragmentOther);
}
public void removeItemAtPosition(int position) {
if (listfavorite != null) {
listfavorite.remove(position);
notifyDataSetChanged();
}
}
public void clearAll() {
if (listfavorite != null) {
listfavorite.clear();
notifyDataSetChanged();
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listfavorite.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return listfavorite.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public View getView(int position, View rowView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if(rowView == null){
rowView = mInflater.inflate(R.layout.activity_view_record, null);
holder = new ViewHolder();
//define those textsview that corresponds to the row views so later we'll retrieve the data from them
holder.idTextView = (TextView) rowView.findViewById(R.id.id);
holder.nameTextView = (TextView) rowView.findViewById(R.id.name);
holder.sectionTextView = (TextView) rowView.findViewById(R.id.section);
holder.packageTextView = (TextView) rowView.findViewById(R.id.packagename);
//retrieve to this strings
id = listfavorite.get(position).getIdFav();
name = listfavorite.get(position).getNameAct();
section = listfavorite.get(position).getSectionName();
packagename = listfavorite.get(position).getPackageAct();
//This will be used for deleting data, because delete data we'll need to pass a long type variable
_id = Long.parseLong(id);
// define the button/textview because the popmenu needs a header!
holder.viewoption=(TextView) rowView.findViewById(R.id.textViewOptions);
holder.viewoption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// so we can use a custom pop menu we'll use this code, first define the contextwrapper
// and define the style of popmenu as second argument! , the style should have as parent
// Widget.AppCompat.PopupMenu ! then
//pass it in popmenu as firstargument
// the gravity.right serve to create margin from right side of the screen
Context wrapper = new ContextThemeWrapper(context, R.style.YOURSTYLE);
//creating a popup menu
PopupMenu popup = new PopupMenu(wrapper, holder.viewoption, Gravity.RIGHT);
//inflating menu from xml resource
popup.inflate(R.menu.options_menu);
// this is really important! to show icon you should use this function, because the icons in normal
// cases don't show up! (we pass the name of the popupmenu inside
setForceShowIcon(popup);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
//delete from database
//Open the database
dbManager = new DBManager(context);
dbManager.open();
dbManager.delete(_id);
//change value of isfav
isFavourite = false;
//save it to sharedprefrenece, the state will be read in other activities and
//show the correspondante state False or true
saveState(isFavourite);
refreshEvents(listfavorite);
notifyDataSetChanged();
//update activity so it'll delete it
// onResume();
break;
case R.id.gotoact:
Intent access_activity = new Intent();
//we use this type of intent because it allow us to use strins for intent
//after retrieving data from row, we'll pass it as second argument
access_activity.setClassName(context,packagename);
context.startActivity(access_activity);
break;
}
return false;
}
});
//displaying the popup
popup.show();
}
});
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
holder.nameTextView.setText(Html.fromHtml(listfavorite.get(position).getNameAct()));
holder.sectionTextView.setText(listfavorite.get(position).getSectionName());
return rowView;
}
public void refreshEvents(final List<Data> events)
{
this.listfavorite.clear();
this.listfavorite.addAll(events);
notifyDataSetChanged();
}
my fragment.java
public class FragmentVideosFav extends Fragment {
private static final String ARG_TITLE = "title";
private String mTitle;
//------Define Database
private DBManager dbManager;
//
List<Data> listContact;
//ListView
private ListView listView;
// Adapter
private FragmentAdapter adapter;
public FragmentVideosFav (){}
public static FragmentVideosFav getInstance(String title) {
FragmentVideosFav fra = new FragmentVideosFav();
Bundle bundle = new Bundle();
bundle.putString(ARG_TITLE, title);
fra.setArguments(bundle);
return fra;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
mTitle = bundle.getString(ARG_TITLE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_other, container, false);
listContact = Getlistfavorite();
//define the list
listView = (ListView) v.findViewById(R.id.list_view);
//if the list is empty! set the correspondante layout!
listView.setEmptyView(v.findViewById(R.id.empty));
// set list to the adapter
adapter= new FragmentAdapter(getActivity(),listContact);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return v;
}
//refresh fragment when switch to ..
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(
isVisibleToUser);
if (getFragmentManager() != null) {
getFragmentManager()
.beginTransaction()
.detach(this)
.attach(this)
.commit();
}
}
// init Data of fragment
private List<Data> Getlistfavorite(){
List<Data> favoritelist = new ArrayList<Data>();
dbManager = new DBManager(getActivity());
dbManager.open();
Cursor c = dbManager.fetchvideo();
//startManagingCursor(c);
int ititle = c.getColumnIndex(_ID);
int idesc = c.getColumnIndex(ACTIVITY_NAME);
int isection = c.getColumnIndex(SECTION_NAME);
int ipath = c.getColumnIndex(PACKAGE_NAME);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
String title = c.getString(ititle);
String desc = c.getString(idesc);
String section = c.getString(isection);
String path = c.getString(ipath);
favoritelist.add(new Data(title, desc , section , path));}
return favoritelist;
}
}
Try this:
View getView(int position, View rowView, ViewGroup parent) {
Data favorite = listfavorite.get(position);
// Etc
case R.id.delete:
dbManager = new DBManager(context);
dbManager.open();
dbManager.delete(_id);
//change value of isfav
isFavourite = false;
//save it to sharedprefrenece, the state will be read in other activities and
//show the correspondante state False or true
saveState(isFavourite);
listfavorite.remove(favorite);
notifyDataSetChanged();

how to save rating of rating bar in list view

i need help to save the rating of rating bar in my list view for each item.My question is how can i do it because the OnItemClickListener does not work.
this is how my custom array adapter looks like
public class CustomArrayAdapter extends ArrayAdapter<String> {
public ArrayList<String> ratings;
private Activity context;
private int[] imageID;
private String[] stdName;
private double[] GPA;
private String[] course;
private String[] rollNo;
public float cRating;
public CustomArrayAdapter(Activity context, int[] imageID, String[] stdName, double[] GPA, String[] course, String[] rollNo) {
super(context, R.layout.row_design, stdName);
this.context = context;
this.imageID = imageID;
this.stdName = stdName;
this.GPA = GPA;
this.course = course;
this.rollNo = rollNo;
}
static class ViewContainer
{
public ImageView stdImage;
public ImageView possibleImage;
public TextView primaryTV;
public TextView secondryTV;
public RatingBar ratingBar;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewContainer viewContainer;
View rowView = convertView;
if(rowView == null) {
//converting the XML file into view objects
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.row_design, null, true);
viewContainer = new ViewContainer();
//getting the refrence of widgets
viewContainer.stdImage = (ImageView) rowView.findViewById(R.id.student_image);
viewContainer.possibleImage = (ImageView) rowView.findViewById(R.id.possibility_image);
viewContainer.primaryTV = (TextView) rowView.findViewById(R.id.primary_text_view);
viewContainer.secondryTV = (TextView) rowView.findViewById(R.id.secondry_text_view);
viewContainer.ratingBar = (RatingBar) rowView.findViewById(R.id.rating_bar);
rowView.setTag(viewContainer);
} else {
viewContainer = (ViewContainer) rowView.getTag();
viewContainer.ratingBar.setRating(0.0f);
rowView.setBackground(null);
}
viewContainer.ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
cRating = rating;
}
});
//setting the possible values to widgets
viewContainer.stdImage.setImageResource(imageID[position]);
viewContainer.primaryTV.setText(stdName[position] + " (GPA:" + GPA[position] + ")");
viewContainer.secondryTV.setText(course[position] + " (RollNo:" + rollNo[position] + ")");
if (GPA[position] < 3.0) {
rowView.setBackgroundResource(android.R.color.holo_red_light);
viewContainer.possibleImage.setImageResource(R.drawable.cross_small);
} else {
viewContainer.possibleImage.setImageResource(R.drawable.tick_small);
}
return rowView;
}
}
and this is my activity where i want to get the rating
public class StudentSelectionActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_selection);
//getting the refrence of list view
ListView listView = (ListView) findViewById(R.id.list);
//creating object of Rating activity to access it's public instances
final MainActivity obj = new MainActivity();
//creating custom adapter
final CustomArrayAdapter adapter = new CustomArrayAdapter(this, obj.imageID, obj.stdName, obj.GPA, obj.course, obj.rollNo);
listView.setAdapter(adapter);
//handling events on click listener of list view
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(StudentSelectionActivity.this, "rating = " + adapter.cRating, Toast.LENGTH_SHORT).show();
}
});
}
#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_selected_students, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Your setOnItemClickListener did not work for adapter class as you are using another clickable class inside adapter. So one option is to use click listener inside adapter class.
As
rowView.setOnClickListener(new View.onClickListener()
{
//Perform your operation.
});
Create an Entry class. This class holds your attributes, like cRating.
Then extend the CustomArrayAdapter for ArrayAdapter<Entry> instead of ArrayAdapter<String>. Change the constructor to something like this
public CustomArrayAdapter(Context context, int layoutResourceID, List<Entry> listItems) {
super(context, layoutResourceID, listItems);
this.context = context;
this.itemList = listItems;
this.layoutResID = layoutResourceID;
}
In your getView method use
EventDetailEntry item = this.itemList.get(position);
to get the corresponding item. Use this item to set the cRating. Then your onItemClicked method should work as expected. Hope that is clear enough.

Android - Update SQLite table from inside Custom ArrayList Adapter

Background:
I'm attempting to create a custom ArrayAdapter for a custom ListView. The list template I'm using to form each row contains a few TextView columns and one Button.
I'm using a SQLite table as the source of the list.
Problem:
I want the Button to capture the current time and write it to my SQLite table [Results] in the column corresponding to the row in which the Button appears. I'm at a loss for how I would do that.
Here is the class that contains the ArrayList
public class ResultsMenu extends ActionBarActivity {
private static final String LOGTAG = "Logtag: " + Thread.currentThread()
.getStackTrace()[2].getClassName(); // log tag for records
// sql elements for selecting boats
private String where = DBAdapter.KEY_RACE_ID + " = " + GlobalContent.activeRace.getId()
+ " AND " + DBAdapter.KEY_RESULTS_VISIBLE + " = 1";
private String orderBy = DBAdapter.KEY_BOAT_CLASS + " DESC ";
//instance of data source
RaceDataSource raceDataSource;
ResultDataSource resultDataSource;
// make a listview instance
ListView myList;
// make button instance for capturing finish time
Button buttonCaptureFinishTime;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results_menu);
//wire data source and open
raceDataSource = new RaceDataSource(this);
resultDataSource = new ResultDataSource(this);
raceDataSource.open();
resultDataSource.open();
// wire list view
myList = (ListView) findViewById(R.id.lvResultList);
//wire button
buttonCaptureFinishTime = (Button) findViewById(R.id.btn_finish_time);
//set onclick listening for listview
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
GlobalContent.setResultsRowID(id);
Intent intent = new Intent(view.getContext(), ResultsEditForm.class);
startActivity(intent);
}
});
}
#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_results_menu, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
Log.i(LOGTAG, " onResume Now");
raceDataSource.open(); // reopen the db
resultDataSource.open(); // reopen the db
//populateListView(); // need to build this
}
#Override
protected void onPause() {
super.onPause();
Log.i(LOGTAG, " onPause NOW");
raceDataSource.close(); // close db to reduce data leak
resultDataSource.close(); // close db to reduce data leak
}
public void populateListView(){
}
}
ArrayAdapter so far
public class ResultsAdapter extends BaseAdapter {
Context mContext; // add context
LayoutInflater inflater; // instance of inflater
// lists of result
private ArrayList<Result> arraylist;
// instance constructor
public ResultsAdapter(Context context, ResultDataSource resultDataSource) {
mContext = context;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Result>();
}
/**
* How many items are in the data set represented by this Adapter.
*
* #return Count of items.
*/
#Override
public int getCount() {
return arraylist.size();
}
#Override
public Object getItem(int position) {
return arraylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView( int index, View view, final ViewGroup parent) {
if (view == null) {
// build inflater to create a new row for each row in the Results table
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.activity_list_template_results, parent, false);
}
final Result result = arraylist.get(index);
Button btn = (Button) view.findViewById(R.id.btn_finish_time); // instance of button
// wire text views and set the associated text to them.
TextView tv = (TextView) view.findViewById(R.id.txt_hd_results_ID);
tv.setText(result.getResultsId() + "");
tv = (TextView) view.findViewById(R.id.txt_hd_results_race_id);
tv.setText(result.getResultsRaceId() + "");
tv = (TextView) view.findViewById(R.id.txt_hd_results_boat_id);
tv.setText(result.getResultsBoatId() + "");
tv = (TextView) view.findViewById(R.id.txt_hd_results_Visible);
tv.setText(result.getResultsVisible() + "");
tv = (TextView) view.findViewById(R.id.txt_hd_results_Name);
tv.setText(result.getBoatName() + "");
tv = (TextView) view.findViewById(R.id.txt_hd_results_Class);
tv.setText(result.getBoatClass() + "");
tv = (TextView) view.findViewById(R.id.txt_hd_results_SailNum);
tv.setText(result.getBoatSailNum() + "");
// set the function of each finish button
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LocalTime localTime = new LocalTime();// capture the current time
// TODO: Add SQLite statement to insert local time into Results table
}
});
return view;
}
}
Inside the onClick method you can create an instance of your database, open it and update the data accordingly.
DatabaseConnection database = new DatabaseConnection(context);
database.getWritableDatabase();

Why is my BaseAdapter class not incrementing the position in getView?

Edit: My issue seems like BaseAdapter just wont post more than 1 Spinner. If I change the array's size to 0, it wont put anything, but anything more than 1 is truncating it. It never passes position 0 from getView() and it never shwows anymore than 1. I have been at it for hours. Is there a reason for this?
I am having an issue with adding Spinners dynamically in a ListView using a BaseAdapter. I tried it before as a test to make sure it could be done correctly in a test class, and it iterates the positions correctly. But now I am doing it again and its failing. What I mean by failing is instead of getView() creating the new Spinner, it never leaves position 0. It still runs. Just never adds more Spinners.
This is my code:
Main Adapter code
public class RemindersAdapter extends BaseAdapter{
Spinner[] shownReminders = new Spinner[1];
TextView[] removeReminders = new TextView[1];
String[] reminders = new String[1]; //this hlds the values of the coresponding spinner
RemindersAdapter mAdapter;
#Override
public int getCount() {
return shownReminders.length;
}
#Override
public Object getItem(int position) {
return shownReminders[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
Log.d("TAG", "A NEW SPINNER AND TEXTVIEW IS CREATED HERE WITH POSITION"+position);
if(view == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.reminder_spinner, parent, false);
}
Spinner reminderSpinner = (Spinner)view.findViewById(R.id.reminder_spinner);
reminderSpinner.setTag(String.valueOf(position));
ArrayAdapter<CharSequence> reminderAdapter = ArrayAdapter.createFromResource(
parent.getContext(), R.array.reminders_array, android.R.layout.simple_spinner_item);
reminderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
reminderSpinner.setAdapter(reminderAdapter);
reminderSpinner.setOnItemSelectedListener(new MyOnReminderSelectedListener());
shownReminders[position] = reminderSpinner;
TextView remove = (TextView)view.findViewById(R.id.remove_reminder);
remove.setTag(String.valueOf(position));
removeReminders[position] = remove;
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("The Array positioning of this remove view is: ", ""+v.getTag());
}
});
return view;
}
public void addReminder() {
Log.d("addReminder METHOD", "The Add Reminder method is running");
Spinner[] temp = new Spinner[shownReminders.length+1];
TextView[] temp2 = new TextView[removeReminders.length+1];
String [] temp3 = new String[reminders.length+1];
for(int i = 0; i < shownReminders.length; i++) {
temp[i] = shownReminders[i];
temp2[i] = removeReminders[i];
temp3[i] = reminders[i];
}
shownReminders = temp;
removeReminders = temp2;
reminders = temp3;
mAdapter.notifyDataSetChanged();//this just makes the adapter refresh itself
}
public void giveYourself(RemindersAdapter adapter) {
mAdapter = adapter;
}
public class MyOnReminderSelectedListener implements OnItemSelectedListener{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
int position = Integer.parseInt(parent.getTag().toString()); //gets the position of the Spinner and puts it in the same index in the reminders array
reminders[position] = parent.getItemAtPosition(pos).toString();
for(int i =0; i < reminders.length; i++) Toast.makeText(parent.getContext(), i+": "+reminders[i], Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// Do nothing for now
}
}//end of MyOnReminderSelectedListener innerclass
}//end of Class
What runs in the Activity
reminderList = (ListView)findViewById(R.id.reminders_list);
reminderAdapter = new RemindersAdapter();
reminderAdapter.giveYourself(reminderAdapter);
reminderList.setAdapter(reminderAdapter);
TextView addReminder = (TextView)findViewById(R.id.add_reminder);
addReminder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("TAG", "The onClick is running !");
reminderAdapter.addReminder();
}
});
I am at a loss because my code looks exactly like my test code, with some modifications in order for it to work with my app. But the information used by the Adapter is pretty much the same. I am going to post the test code as well so you guys can see the code that works.
Test Code
public class RemindersAdapter extends BaseAdapter{
Spinner[] shownReminders = new Spinner[1];
ArrayList<TextView> removeSpinner = new ArrayList<TextView>();
Context mContext;
public RemindersAdapter(Context context) {
mContext = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return shownReminders.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return shownReminders[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
Log.d("TAG", "Number of times this is running"+position);
Log.d("TAG", "Address of the Spinner Object"+shownReminders[position]);
if(view == null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.reminder_spinner, parent, false);
}
Spinner reminderSpinner = (Spinner)view.findViewById(R.id.reminders_spinner);
reminderSpinner.setTag("1");
ArrayAdapter<CharSequence> reminderAdapter = ArrayAdapter.createFromResource(
parent.getContext(), R.array.reminders_array, android.R.layout.simple_spinner_item);
reminderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
reminderSpinner.setAdapter(reminderAdapter);
reminderSpinner.setOnItemSelectedListener(new MyOnReminderSelectedListener());
shownReminders[position] = reminderSpinner;
TextView remove = (TextView)view.findViewById(R.id.remove_reminder);
remove.setTag(position);
removeSpinner.add(remove);
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = Integer.parseInt(v.getTag().toString());
removeSpinner.remove(pos);
Spinner[] temp = new Spinner[shownReminders.length-1];
for(int i =0; i < shownReminders.length; i++) {
if(i == pos || i > pos) {
temp[i-1] = shownReminders[i];
} else {
temp[i] = shownReminders[i];
}
}
//Here i should refresh somewhow
}
});
return view;
}
public void addReminder() {
Spinner[] temp = new Spinner[shownReminders.length+1];
for(int i = 0; i < shownReminders.length; i++) {
temp[i] = shownReminders[i];
}
shownReminders = temp;
}
/*
* Listener for when the reminder spinner gets a value the user entered
* */
public class MyOnReminderSelectedListener implements OnItemSelectedListener{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
//does nothing for now
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// Do nothing for now
}
}//end of MyOnReminderSelectedListener innerclass
I also have a question as to why the Adapter runs itself so much. For examples, using the Log, I noticed it calls getView() twice for no apparent reason. Its weird that it has this behavior. I guess I don't understand BaseAdapter so well.
This error will happen if you put a ListView inside a ScrollView. ListView itself does vertical scroll so it must not be put into a ScrollView.
An adapter will call getView when listView needs a new item to show. So, if your listView has no scroll, no new item will be created, and no call to getView will be made.
But you should not store all spinner objects, or create new objects in getView. That`s because it will be slow and maybe waste of memory.

Categories

Resources