I am working on a checkbox listview. What I have done so far is populated the list from local db, get all the checked item's databse id using the setOnCheckedChangeListener and store it in a separate table in my local db. This is how my code looks:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null){
dbHelper = new DBHelper(con);
database = dbHelper.getWritableDatabase();
switch (getItemViewType(position)){
case DYNAMIC_OBJECTIVE:
convertView = layoutInflater.inflate(R.layout.objective_list_view, null);
break;
case STATIC_OBJECTIVE:
convertView = layoutInflater.inflate(R.layout.other_objective_list_view, null);
break;
}
switch (getItemViewType(position)){
case DYNAMIC_OBJECTIVE:
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.objectiveCheckBox);
checkBox.setText(((Objectives)list.get(position)).getObjectiveTitle());
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
selectedObjectivesMap.put(((Objectives)list.get(position)).getObjectiveID(), "YES");
}else{
selectedObjectivesMap.put(((Objectives)list.get(position)).getObjectiveID(), "NO");
}
}
});
break;
case STATIC_OBJECTIVE:
TextView checkBoxOther = (TextView) convertView.findViewById(R.id.objectiveOtherCheckBox);
final TextView objectiveOtherET = (TextView) convertView.findViewById(R.id.objectiveOtherEditText);
checkBoxOther.setText((String)list.get(position));
//ll = (LinearLayout)convertView.findViewById(R.id.linearLayoutOther);
//viewNew = layoutInflater.inflate(R.layout.other_objective_row, null);
ImageButton imageButton = (ImageButton) convertView.findViewById(R.id.addOtherObjectiveTextBox);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), "Clicked123", Toast.LENGTH_SHORT).show();
final Dialog dialog = new Dialog(v.getContext());
dialog.setContentView(R.layout.otherobjectivedialog);
final EditText enterObjET = (EditText) dialog.findViewById(R.id.enterObjEditText);
Button closeEnterObjBtn = (Button) dialog.findViewById(R.id.closeEnterObjDialog);
Button objConfirmBtn = (Button) dialog.findViewById(R.id.enterObjConfirmBtn);
closeEnterObjBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
objConfirmBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String enteredObj = enterObjET.getText().toString();
if(enteredObj.equals("")){
Toast.makeText(v.getContext(), "Please write a objective", Toast.LENGTH_LONG).show();
}else {
objectiveOtherET.setText(objectiveOtherET.getText().toString()+ " \n" + enteredObj);
otherObjList.add(enteredObj);
dialog.dismiss();
}
}
});
dialog.show();
/* LinearLayout linearLayoutNew = new LinearLayout(con);
linearLayoutNew.setOrientation(LinearLayout.VERTICAL);
et = new EditText(con);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
et.setLayoutParams(p);
et.setHint("Set some objective");
linearLayoutNew.addView(et);
ll.addView(linearLayoutNew);*/
}
});
break;
}
}
return convertView;
}
and this is how I'm populating my list:
ArrayList<Object> objectiveList = new ArrayList<>();
Cursor crs = database.rawQuery("SELECT * FROM "+ ItemsTable.TABLE_OBJECTIVE +"", null);
while(crs.moveToNext())
{
String title = crs.getString(crs.getColumnIndex("title"));
int objectiveID = crs.getInt(crs.getColumnIndex("id"));
objectiveList.add(new Objectives(objectiveID, title));
}
crs.close();
objectiveList.add("Others");
listView.setAdapter(new ObjectivesAdapter(getActivity(), objectiveList));
viewPager = (ViewPager) getActivity().findViewById(R.id.pager);
PROBLEM:
This all works perfect but now I want to edit the same information. All I want is the existing checkbox id's (that were checked and store in my db) should be checked when I come back to this view. I have queried the data and I have the IDs but I don't know how to check the checkboxes based on their IDs.
Cursor crsCheckObj = database.rawQuery("SELECT * FROM "+ ItemsTable.TABLE_PLAN_OBJECTIVE_MAP +" WHERE "
+ ItemsTable.COLUMN_PLAN_OBJECTIVE_MAP_PLANID +"='"+ Info.getInstance().getPlanVisitID() +"'", null);
if(crsCheckObj.getCount() > 0){
while (crsCheckObj.moveToNext()){
//Here IDs should match in order to check the checkboxes
}
}
crsCheckObj.close();
For that you can simply use checkbox.setChecked(true)
if it do not work then try following:
checkbox.postDelayed(new Runnable() {
#Override
public void run() {
checkbox.setChecked(true);
}
},100);
First setTag() for your checkbox like this:
checkBox.setTag(((Objectives)list.get(position)).getObjectiveID());
then all you need to is something like this:
Cursor crsCheckObj = database.rawQuery("SELECT * FROM "+ ItemsTable.TABLE_PLAN_OBJECTIVE_MAP +" WHERE "
+ ItemsTable.COLUMN_PLAN_OBJECTIVE_MAP_PLANID +"='"+ Info.getInstance().getPlanVisitID() +"'", null);
if(crsCheckObj.getCount() > 0){
while (crsCheckObj.moveToNext()){
if(((Integer) checkBox.getTag()) == crsCheckObj.getInt(crsCheckObj.getColumnIndex("objective_id"))){
checkBox.setChecked(true);
}
}
}
crsCheckObj.close();
Related
I read some posts and found that reQuery() is deprecated and some suggested using SwapCursor() or ChangeCursor().
I have a Favorite button on whose click I update DB and change color of the Button. When I scroll and come back to particular view(and Button) color is reset.
I know it is because view is recycled. I have a condition based on a DB column value to set the color of the Button.
I want view to get updated values from DB after I press the Button. For which I have to refresh/requery Cursor/DB.
How do I do that with CursorAdapter keeping in mind that my min. API is 19?
UPDATE
CursorAdapter code:
public class ToDoCursorAdapter extends CursorAdapter {
SparseBooleanArray selectionArrayAr = new SparseBooleanArray();
SparseBooleanArray selectionArrayRef = new SparseBooleanArray();
SparseBooleanArray selectionArrayFav = new SparseBooleanArray();
//Boolean isSet = false;
private MainButtons_Interface mAdapterCallback;
public ToDoCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ViewHolderItem viewHolder = new ViewHolderItem();
View rowView = LayoutInflater.from(context).inflate(R.layout.listview, parent, false);
viewHolder.engTextV = (TextView) rowView.findViewById(R.id.engText);
viewHolder.arTextV = (TextView) rowView.findViewById(R.id.arabText);
viewHolder.buttonIAV = (Button) rowView.findViewById(R.id.buttonIA); //For Arabic Text
viewHolder.refTextV = (TextView) rowView.findViewById(R.id.refText);
viewHolder.buttonIRV = (Button) rowView.findViewById(R.id.buttonIR); //For Ref Text
viewHolder.buttonIFV = (ImageButton) rowView.findViewById(R.id.buttonF);
rowView.setTag(viewHolder);
return rowView;
}
#Override
public void bindView(final View view, final Context context, final Cursor cursor) {
final ViewHolderItem viewHolder = (ViewHolderItem) view.getTag();
String arabic = cursor.getString(cursor.getColumnIndexOrThrow("PlainArab_Text")).trim().replaceAll("[\n]{2,}", "TWOFEEDS").replaceAll("\n", " ").replaceAll(" +", " ").replaceAll("<br/>", "\n").replaceAll("TWOFEEDS", "\n") + "\n";
String english = cursor.getString(cursor.getColumnIndexOrThrow("PlainEng_Text")).trim().replaceAll("[\n]{2,}", "TWOFEEDS").replaceAll("\n", " ").replaceAll(" +", " ").replaceAll("<br/>", "\n").replaceAll("TWOFEEDS", "\n") + "\n";
String ref = cursor.getString(cursor.getColumnIndexOrThrow("REF")).trim().replaceAll("<br/> <br/>", " ").replaceAll("<br/>", "\n");
final Integer HadithID = cursor.getInt(cursor.getColumnIndexOrThrow("ID"));
final Integer IsFav = cursor.getInt(cursor.getColumnIndexOrThrow("IsFavorite"));
viewHolder.arTextV.setText(arabic);
viewHolder.engTextV.setText(english);
viewHolder.refTextV.setText(ref);
final int position = cursor.getPosition();
boolean isSelectedA = selectionArrayAr.get(position);
boolean isSelectedR = selectionArrayRef.get(position);
boolean isSelectedF = selectionArrayFav.get(position);
if (isSelectedA) {
viewHolder.arTextV.setVisibility(view.GONE);
viewHolder.buttonIAV.setText("Show Arabic Version");
} else if (!isSelectedA){
viewHolder.arTextV.setVisibility(view.VISIBLE);
viewHolder.buttonIAV.setText("Hide Arabic Version");
}
if (isSelectedR) {
viewHolder.refTextV.setVisibility(view.GONE);
viewHolder.buttonIRV.setText("Show Refrence");
} else if (!isSelectedR){
viewHolder.refTextV.setVisibility(view.VISIBLE);
viewHolder.buttonIRV.setText("Hide Refrence");
}
//boolean isSelectedF = selectionArrayFav.get(position);
if(isSelectedF) {
viewHolder.buttonIFV.setImageResource(R.drawable.favoritebutton_afterclick);
} else if (!isSelectedF){
viewHolder.buttonIFV.setImageResource(R.drawable.favoritebutton);
}
//Arabic Button
viewHolder.buttonIAV.setOnClickListener(
new View.OnClickListener()
{ #Override
public void onClick(View v) {
boolean isSelectedAc = selectionArrayAr.get(position);
if(!isSelectedAc) {
viewHolder.arTextV.setVisibility(v.GONE);
viewHolder.buttonIAV.setText("Show Arabic Version");
setSelectedAr(position, true);
} else if (isSelectedAc){
viewHolder.arTextV.setVisibility(v.VISIBLE);
setSelectedAr(position, false);
viewHolder.buttonIAV.setText("Hide Arabic version");
}
}
}
);
//Ref Button
viewHolder.buttonIRV.setOnClickListener(
new View.OnClickListener()
{ #Override
public void onClick(View v) {
boolean isSelectedRc = selectionArrayRef.get(position);
if(!isSelectedRc) {
viewHolder.refTextV.setVisibility(v.GONE);
viewHolder.buttonIRV.setText("Show Reference");
setSelectedRef(position, true);
} else if (isSelectedRc){
viewHolder.refTextV.setVisibility(v.VISIBLE);
setSelectedRef(position, false);
viewHolder.buttonIRV.setText("Hide Reference");
}
}
}
);
//Fav Button
viewHolder.buttonIFV.setOnClickListener(
new View.OnClickListener()
{ #Override
public void onClick(View v) {
boolean isSelectedF = selectionArrayFav.get(position);
boolean IsSet = ((ListViewActivity) context).addRemFav(HadithID);
String mess ="";
if(IsSet){
mess = "Hadith add to Favorite list";
} else if(!IsSet){
mess = "Hadith removed from Favorite list";
}
if(!isSelectedF) {
viewHolder.buttonIFV.setImageResource(R.drawable.favoritebutton_afterclick);
setSelectedF(position, true);
} else if (isSelectedF){
viewHolder.buttonIFV.setImageResource(R.drawable.favoritebutton);
setSelectedF(position, false);
}
Toast.makeText(v.getContext(), mess, Toast.LENGTH_SHORT).show();
}
}
);
}
// our ViewHolder.
static class ViewHolderItem {
TextView engTextV;
TextView arTextV;
TextView refTextV;
Button buttonIAV;
Button buttonIRV;
ImageButton buttonIFV;
}
// Method to mark items in selection
public void setSelectedAr(int position, boolean isSelected) {
selectionArrayAr.put(position, isSelected);
}
public void setSelectedRef(int position, boolean isSelected) {
selectionArrayRef.put(position, isSelected);
}
public void setSelectedF(int position, boolean isSelected) {
selectionArrayFav.put(position, isSelected);
}
UPDATE
I added this logic to my function which was called on clicking the Button.
Cursor todoCursor1 = hadDB.rawQuery("SELECT ID as _id, * FROM HAD_TABLE WHERE ID < 7001 ", null);
todoAdapter.changeCursor(todoCursor1);
Basically, you just need to requery DB so that you get updated records/Data and then change your current cursor with new one, todoCursor1 is my case above.
Also, changeCursor() will close your current cursor, in case you would want to go back to old cursor you should use swapCursor() instead as it will return you old cursor.
Now my only thing I want to know is, if this will work for APIs 19 and up.
I added this logic to my function which was called on clicking the Button.
Cursor todoCursor1 = hadDB.rawQuery("SELECT ID as _id, * FROM HAD_TABLE WHERE ID < 7001 ", null);
todoAdapter.changeCursor(todoCursor1);
Basically, you just need to requery DB so that you get updated records/Data and then change your current cursor with new one, todoCursor1 is my case above.
Also, changeCursor() will close your current cursor, in case you would want to go back to old cursor you should use swapCursor() instead as it will return you old cursor.
I am inflating the passenger_details_layout in main_passenger_details_layout.At run time i am setting the values in TextView . I am setting up pax_id that is invisible for every row that i am inflating in it.So on click of passenger_details_layout i want to call a new activity and pass the pax_id to the new activity.
Pax_id will be like 1,2,3 for every time for loop will run.So on click of 1 row i want to get the pax_id of first row that i have set.
Please help how could i do this Will be thank full to you.
Code to Infalate
ItinResponse data = obj.parseXMLData(fXmlFile);
List<SectorRecords> sectorList = data.getSectorRecordsDetails();
int items = 0;
List<PassengerDetails> listdata = data.getPaxDetails();
int i = 0;
for (PassengerDetails elements : listdata) {
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout layout = (RelativeLayout) inflater.inflate(
R.layout.passenger_details_layout, main, false);
firstName = (TextView) layout.findViewById(R.id.first_pax_name);
pax_id = (TextView) layout.findViewById(R.id.pax_id);
firstName.setText(elements.getFirstName() + " "
+ elements.getLastName());
pax_id.setText(elements.getPaxId());
main.addView(layout, i);
i++;
layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)"+pax_id.getText(), Toast.LENGTH_LONG).show();
}
});
On every row is showing the last pax id
You have to do nothing what you are trying
Replace this
pax_id.setText(elements.getPaxId());
to
layout.setId(Integer.parseInt(elements.getPaxId()));
And in your Layout Click
layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)"+layout.getId(), Toast.LENGTH_LONG).show();
}
});
Every time you will get the Unique ID that u want to set
All the best...!!!!
Use
TextView paxView = (TextView)v.findViewById(R.id.pax_id);
String pax_value = paxView.getText().toString();
On button click of every row do like this
Intent intent=new Intent(this,YOUR_NEXT_ACTIVIY.class);
intent.putExtra("paxid", pax_id.getText());
startActivity(intent);
ItinResponse data = obj.parseXMLData(fXmlFile);
List<SectorRecords> sectorList = data.getSectorRecordsDetails();
int items = 0;
List<PassengerDetails> listdata = data.getPaxDetails();
int i = 0;
for (PassengerDetails elements : listdata) {
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout layout = (RelativeLayout) inflater.inflate(
R.layout.passenger_details_layout, main, false);
firstName = (TextView) layout.findViewById(R.id.first_pax_name);
pax_id = (TextView) layout.findViewById(R.id.pax_id);
firstName.setText(elements.getFirstName() + " "
+ elements.getLastName());
pax_id.setText(elements.getPaxId());
layout.setTag(elements.getPaxId());
main.addView(layout, i);
i++;
layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String paxId = v.getTag().toString();
// do some staff
}
});
}
// try this
ItinResponse data = obj.parseXMLData(fXmlFile);
List<SectorRecords> sectorList = data.getSectorRecordsDetails();
int items = 0;
List<PassengerDetails> listdata = data.getPaxDetails();
int i = 0;
for (PassengerDetails elements : listdata) {
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout layout = (RelativeLayout) inflater.inflate(
R.layout.passenger_details_layout, main, false);
firstName = (TextView) layout.findViewById(R.id.first_pax_name);
pax_id = (TextView) layout.findViewById(R.id.pax_id);
firstName.setText(elements.getFirstName() + " "
+ elements.getLastName());
pax_id.setText(elements.getPaxId());
layout.setTag(elements);
main.addView(layout, i);
i++;
layout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
PassengerDetails elements = (PassengerDetails) v.getTag();
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)"+elements.getPaxId(), Toast.LENGTH_LONG).show();
}
});
}
I have a listview to populate data with a CustomAdapter as shown below by code.
1.) The listview rows are clickable and onItemClick I show up two buttons retake/review.
2.) When I click on other row the buttons which were visible on the previous row should hide.
3.) When I scroll the list all buttons are again invisible , that should not happen.
I have achieved the point no. 1 by this code , but how could I achieve 2,3. How could I modify getView() method of adapter or onItemClick() so that things work proper.
//Initialized listview with adapter
AttempListView.setAdapter(new AttemptedExcerciseAdapter(mAttempRecord,AttemptedExercise.this));
//A different adapter class to place values
public class AttemptedExcerciseAdapter extends BaseAdapter{
HashMap<Integer, AttemptedRecord> mHashMap;
Context mContext;
LinearLayout mLLButton;
public AttemptedExcerciseAdapter() {
// TODO Auto-generated constructor stub
}
public AttemptedExcerciseAdapter(HashMap<Integer, AttemptedRecord> mAttempRecord,Context mContext) {
this.mHashMap = mAttempRecord;
this.mContext=mContext;
}
#Override
public int getCount() {
return mHashMap.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
if (convertView == null) {
#SuppressWarnings("static-access")
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(AttemptedExercise.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.exerciselistlayout, null);
}
TextView attempChapter_name = (TextView) convertView.findViewById(R.id.TVchapterexercisechapterName);
TextView attemptQues = (TextView) convertView.findViewById(R.id.tvexercisesuccessrate);
TextView attemptSR = (TextView) convertView.findViewById(R.id.tvexerciseperquestiontime);
Button ReviewButton = (Button) convertView.findViewById(R.id.ReviewButton);
Button RetakeButton = (Button) convertView.findViewById(R.id.RetakeButton);
LinearLayout mLLtext = (LinearLayout) convertView.findViewById(R.id.LLText);
mLLButton = (LinearLayout) convertView.findViewById(R.id.LLButton);
mLLButton.setVisibility(View.INVISIBLE);
mLLtext.setVisibility(View.VISIBLE);
System.out.println("data value is..."+position+mHashMap.get(position + 1).getChapter_name());
attempChapter_name.setText(mHashMap.get(position+1).getChapter_name());
attemptQues.setText(" " + mHashMap.get(position+1).getTimePerQues() + " sec/ques");
attemptSR.setText(" " + mHashMap.get(position+1).getSuccess_rate() + " %");
return convertView;
}
}
//Item click listener for listview
public class ExcerciseItemClickListener implements OnItemClickListener {
ArrayList<Integer> rowNo=new ArrayList<Integer>();
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
System.out.println("click working..."+arg2);
arg1.findViewById(R.id.LLButton).setVisibility(View.INVISIBLE);
rowNo.clear();
rowNo.add(arg2);
if(rowNo.size()==1)
{
AttemptedRecord mRecordExcerciseItem = mAttempRecord.get(arg2 + 1);
final int chapter_id = mRecordExcerciseItem.getChapter_id();
final int test_id = mRecordExcerciseItem.getTest_id();
final int subject_id = mRecordExcerciseItem.getSubject_id();
System.out.println("attempted list size is..."+mAttempRecord.size());
arg1.findViewById(R.id.LLText).setVisibility(View.INVISIBLE);
arg1.findViewById(R.id.LLTake).setVisibility(View.INVISIBLE);
arg1.findViewById(R.id.LLButton).setVisibility(View.VISIBLE);
Button review=(Button) arg1.findViewById(R.id.ReviewButton);
Button retake=(Button) arg1.findViewById(R.id.RetakeButton);
review.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBHelper mDbHelper = new DBHelper(AttemptedExercise.this);
mDbHelper.createOrOpenDatabase("Dashboard");
Cursor chpater_exercise_Cursor = mDbHelper.rawQuery("select current_test_id from practice_test_summary where test_id="+test_id+" order by test_datetime desc limit 1");
chpater_exercise_Cursor.moveToFirst();
Long current_test_id =chpater_exercise_Cursor.getLong(0);
chpater_exercise_Cursor.close();
System.out.println("value of current test id is...."+current_test_id);
Intent reviewIntent = new Intent(AttemptedExercise.this, PracticeReview.class);
reviewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
if (current_test_id > 0) {
reviewIntent.putExtra("current_test_id", current_test_id);
startActivity(reviewIntent);
}
}
});
retake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("test id value when test starts is... "+test_id);
Toast.makeText(AttemptedExercise.this, "chapter_id" + chapter_id + " course_id" + " test_id" + test_id + " subject_id" + subject_id, Toast.LENGTH_LONG).show();
StartTest(4, subject_id, chapter_id, test_id);
}
});
}
}
}
In getView, you hide the button and text,that's why the view dispears when you scrolling。
mLLButton.setVisibility(View.INVISIBLE);
mLLtext.setVisibility(View.VISIBLE);
In your click listener you should record the position of the selected row, and in getView, you need to set view's visilibity status based on the postion of the view.
if you can mange to add ClickListeners of the list in getView like this
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
curruntButtonClickPosition=position;
//Visible you button here
notifyDataSetChanged();
}
});
and in getView
if(curruntButtonClickPosition=position)
//mLLButton visible
else
//mLLButton invisible
add curruntButtonClickPosition globle variable in AttemptedExcerciseAdapter class and init with -1.
I have a custom ListView with two button and I when I click either button on any row I want to get the text label on the Listview and for now just popup a toast with it. So far nothing has worked I keep getting the last item in my array.
Here is a screen shot to give you a better idea of what i mean
Here is my Adapter subclass for my custom ListView
static final String[] Names =
new String[] { "John", "Mike", "Maria", "Miguel"};
class MyArrayAdapter extends ArrayAdapter<String> {
private final Context context;
int which;
public MyArrayAdapter(Context context, String[] pValues) {
super(context, R.layout.main, pValues);
this.context = context;
values = pValues;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.main, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
Button call = (Button) rowView.findViewById(R.id.button1);
Button chat = (Button) rowView.findViewById(R.id.button2);
textView.setText(values[position]);
// Change icon based on name
s = values[position];
which = position;
call.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = values[which];
Toast.makeText(CustomListView.this, name, Toast.LENGTH_SHORT).show();
}
});
return rowView;
}
}
Edit:
String name = textView.getText().toString();
RelativeLayout ll = (RelativeLayout)v.getParent();
textView = (TextView)ll.findViewById(R.id.label);
Toast.makeText(CustomListView.this, name,
Toast.LENGTH_SHORT).show();
Easy to do:
call.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
RelativeLayout rl = (RelativeLayout)v.getParent();
TextView tv = (TextView)rl.findViewById(R.id.label);
String text = tv.getText().toString();
Toast.makeText(CustomListView.this, text, Toast.LENGTH_SHORT).show();
}
});
use setTag attribute of the View..............
as
Button call = (Button) rowView.findViewById(R.id.button1);
call.setTag(position);
and
call.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int which = -1;
Obejct obj = v.getTag();
if(obj instaceof Integer){
which = ((Integer)obj).intValue();
}
if(which >-1){
String name = values[which];
Toast.makeText(CustomListView.this, name, Toast.LENGTH_SHORT).show();
}
}
});
If you have a ListActivity, and you're not using your own adapter, you can still get the list item belonging to the tapped button, like so:
In your layout file of the list row:
<ImageButton
android:id="#+id/button_call"
android:layout_height="48dip"
android:layout_width="48dip"
android:contentDescription="Call"
android:onClick="callBuddy"
android:src="#drawable/call_button_image"
/>
In your ListActivity:
public void callBuddy(View view) {
int position = getListView().getPositionForView((View) view.getParent());
Buddy buddyToCall = (Buddy) getListView().getItemAtPosition(position);
Toast.makeText(MyListActivity.this, String.format("Calling your buddy %s.", buddyToCall.name), Toast.LENGTH_SHORT).show();
}
simply use getItem() and pass the position
Ex:getItem(position).getID()
here getID() method is getter method
Set onClick="click" to xml of button/image/etc...
and in your Activity, do:
public void click(View v) {
final int position = getListView().getPositionForView(v);
String text = getListView().getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext, text, Toast.LENGTH_SHORT).show();
}
I have ONE annoying problem with SimpleCursorAdapter. My programm has list view and ListActivity. Each row has it's own layout:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:layout_width="fill_parent"
android:orientation="horizontal" android:weightSum="1.0">
<TableRow>
<TextView android:id="#+id/task_time"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textSize="24sp" android:text="Time">
</TextView>
<LinearLayout android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="fill_parent">
<TextView android:id="#+id/task_name"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textSize="20sp" android:text="Name">
</TextView>
<TextView android:id="#+id/task_categoty"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Category" android:textSize="12sp">
</TextView>
</LinearLayout>
<TextView android:id="#+id/task_state"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="State" android:textSize="12sp">
</TextView>
<CheckBox android:id="#+id/task_enabled"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:focusable="false">
</CheckBox>
</TableRow>
Tasks are stored in SQLite database. I have DAO object (singleton) to access the database.
TaskDao:
public void updateEnabled(int id, boolean enabled){
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(ENABLED_COLUMN, enabled==true?1:0);
Log.i(TAG, "update to " + cv.get(ENABLED_COLUMN) );
try{
db.beginTransaction();
db.update(TASK_TABLE, cv, ID_COLUMN+"=?", new String[]{id+""});
db.setTransactionSuccessful();
} catch (SQLException e) {
Log.i(TAG, "edit task failed!");
} finally {
db.endTransaction();
if (db != null)
db.close();
}
}
and the Cursor method for ListActivity:
public Cursor getTasks(){
SQLiteDatabase db = dbHelper.getReadableDatabase();
return db.query(TASK_TABLE, COLUMNS, null, null, null, null, NAME_COLUMN);
}
I extended SimpleCursorAdapter (TaskDbAdapter) like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView = inflater.inflate(R.layout.task_list_row, null);
}
Cursor c = getCursor();
c.moveToPosition(position);
Log.i(TAG, "getView " + position + " = " + c.getInt(enabledIdx));
enabled.setTag(c.getInt(c.getColumnIndex(BaseColumns._ID)));
enabled.setChecked(c.getInt(enabledIdx)>0?true:false);
enabled.setOnClickListener(this);
return convertView;
}
#Override
public void onClick(View v) {
CheckBox box = (CheckBox) v;
Integer id = (Integer)box.getTag();
TaskDao.getInstance(context).updateEnabled(id.intValue(), box.isChecked());
}
And at last I use all the above stuff in my main ListActivity
private void refreshList(){
c = TaskDao.getInstance(this).getTasks();
startManagingCursor(c);
adapter = new TaskDbAdapter(this, R.layout.task_list_row, c, new String[]{TaskDao.ENABLED_COLUMN}, new int[]{R.id.task_enabled});
setListAdapter(adapter);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task);
getListView().setItemsCanFocus(false);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setVerticalScrollBarEnabled(true);
registerForContextMenu(getListView());
getListView().setOnCreateContextMenuListener(this);
refreshList();
}
#Override
protected void onResume() {
super.onResume();
refreshList();
}
#Override
protected void onPause() {
super.onPause();
}
Everything works fine. But CheckBoxes loose their states. For instance I check my first column and scroll the list down. In my trace before press I have:
getView 0 = 0
getView 2 = 0
getView 3 = 0
then
uptate to 1
and then (when I scroll up to the first element)
getView 0 = 0
getView 2 = 0
getView 3 = 0
I tried to make getCursor().requery(); in my TaskDbAdapter onClick method. But then I saw no items in the list! And exception because of cursor management(connection was closed by android). When I write startManagingCursor(c); in refreshList() method then check and uncheck methods don't work.
Please, Help!
I didn't read all your source so my suggestion may be totally wrong, but I will give a try.
Take a look at the documentation of BaseAdapter class.
public void notifyDataSetChanged ()
may do the work.
You also can register Observer for this...
public void registerDataSetObserver (DataSetObserver observer)
I struggled with this as well. I ended up storing all checked boxes in the db as either 0 or 1. Then I check their state from the database to determine if they are marked or not.
public class DetailCursorAdapter extends SimpleCursorAdapter {
private Cursor c;
private Context context;
public DetailCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.c = c;
this.context = context;
}
public View getView(int pos, View inView, ViewGroup parent) {
View v = inView;
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.check_list, null);
}
Log.i("pos = ..................", "pos = "+pos);
this.c.moveToPosition(pos);
//this.c.moveToPosition(this.c.getInt(this.c.getColumnIndex("_id")));
CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);
cBox.setTag(this.c.getInt(this.c.getColumnIndex("_id")));
/*
* when reloading the list, check for chkd status, this is broken. Need to query db directly.
*/
EventDbAdapter mDbHelper = new EventDbAdapter(context);
mDbHelper.open();
int idTag = (Integer) cBox.getTag();
int checked = mDbHelper.selectChk(idTag);
mDbHelper.close();
Log.i("results from selectChk.....................", ""+checked);
if (checked == 1) {
cBox.setChecked(true);
} else {
cBox.setChecked(false);
}
/*
* Populate the list
*/
TextView txtdateTime = (TextView)v.findViewById(R.id.time);
txtdateTime.setText(this.c.getString(this.c.getColumnIndex("time")));
TextView txtdateEvent = (TextView)v.findViewById(R.id.event);
txtdateEvent.setText(this.c.getString(this.c.getColumnIndex("event")));
TextView txtdateLocation = (TextView)v.findViewById(R.id.location);
txtdateLocation.setText(this.c.getString(this.c.getColumnIndex("location")));
ImageView arrow = (ImageView) v.findViewById(R.id.arrowId);
arrow.setImageResource(R.drawable.rightarrow);
Log.i("if chk in db is = 1 then set checked.........",this.c.getString(this.c.getColumnIndex("checked")) +" " +this.c.getString(this.c.getColumnIndex("time")));
/*
* Controls action based on clicked list item (background)
*/
View lv = v.getRootView();
lv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View lv) {
CheckBox cBox = (CheckBox) lv.findViewById(R.id.bcheck);
// id holds the rowid of each event. pass this to a new activity to query for description
// Call Event Detail
String id = cBox.getTag().toString();
Intent i = new Intent(context, EventDetail.class);
//i.putExtra("description", c.getString(c.getColumnIndex("description")));
i.putExtra("_id", id);
context.startActivity(i);
}
});
/*
* Begin - Controls action based on clicked Text only
txtdateEvent.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
CharSequence charseq = "Darth Vader is alive";
Toast.makeText(context, charseq, Toast.LENGTH_SHORT).show();
}
});
* End - Controls action based on clicked Text only
*/
/*
* Controls action based on clicked checkbox
*/
cBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
EventDbAdapter mDbHelper = new EventDbAdapter(context);
mDbHelper.open();
CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);
if (cBox.isChecked()) {
//cBox.setChecked(false);
CharSequence charseq = "Added to My Schedule";
Toast.makeText(context, charseq, Toast.LENGTH_SHORT).show();
// Update the database for each checked item
mDbHelper.updateChecked(cBox.getTag().toString(), "1");
c.requery();
// Verify that the db was updated for debugging purposes
String event = c.getString(c.getColumnIndex("event"));
int id = (Integer) cBox.getTag();
Log.i("checked _id...........", "id= " + id + " " +c.getString(c.getColumnIndex("_id")));
Log.i("checked checked...........", ""+c.getString(c.getColumnIndex("checked")));
} else if (!cBox.isChecked()) {
//cBox.setChecked(true);
CharSequence charseq = "Removed from My Schedule";
Toast.makeText(context, charseq, Toast.LENGTH_SHORT).show();
// checkList.remove(cBox.getTag());
//checkList.add((Integer) cBox.getTag());
String event = c.getString(c.getColumnIndex("event"));
//int id = c.getInt(c.getColumnIndex("_id"));
int id = (Integer) cBox.getTag();
mDbHelper.updateChecked(cBox.getTag().toString(), "0");
c.requery();
//int sqlresult = mDbHelper.selectChk(id, event);
//Log.i("sqlresult checked value after update...........", ""+ sqlresult);
//Log.i("unchecked _id...........", ""+c.getString(c.getColumnIndex("_id")));
//Log.i("unchecked checked...........", ""+c.getString(c.getColumnIndex("checked")));
}
//mDbHelper.close();
}
});
return(v);
}
}