Android: View doesn't show up again in Listview / Adapter? - android

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.

Related

Empty Listbox is showing in the Listview

i have created a list view in my android project and its showing an empty list at the beginning of the ListView. All the data is showing accurately from the database. but it creates a null list at the top of the List view. for example if we are taking one record from the database, two records are showing. first record is null as shown in the picture here
I dont know the fault is in the custom adapter or the listview. several days i have searched for an solution and could not find. Please assist me to complete the project. thanks.
below i will past my custom adapter code and the ListView
Custom Adapter
else {
LISTVIEW = (ListView) findViewById(R.id.listView1);
customAdapter = new CustomAdapter();
LISTVIEW.setAdapter(customAdapter);
LISTVIEW.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
LISTVIEW.setStackFromBottom(true);
}
static class ViewHolder {
TextView ord_num;
TextView cus_name;
TextView cus_tel;
TextView ord_status;
}
class CustomAdapter extends BaseAdapter {
#Override
public int getCount() {
return ID_ArrayList.size() + 1;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return -1;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder = null;
if (view == null) {
view = getLayoutInflater().inflate(R.layout.listtemplate, viewGroup,false);
holder = new ViewHolder();
holder.ord_num = (TextView) findViewById(R.id.lblID);
holder.cus_name = (TextView) findViewById(R.id.cus_name);
holder.cus_tel = (TextView) findViewById(R.id.cus_tel);
holder.ord_status = (TextView) findViewById(R.id.ord_status);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
try {
holder.ord_num.setText("Order ID :" + ID_ArrayList.get(i));
holder.cus_name.setText("Name : " + NAME_ArrayList.get(i));
holder.cus_tel.setText("Telephone No : " + PHONE_NUMBER_ArrayList.get(i));
holder.ord_status.setText("Status : " + STATUS_ArrayList.get(i));
} catch (Exception ex) {
System.out.println(ex);
}
final int a=i;
view.findViewById(R.id.item_info).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, View_Items.class);
String x = getItem(a).toString();
String y = ID_ArrayList.get(Integer.parseInt(x)-1).toString();
AlertDialog.Builder alt = new AlertDialog.Builder(MainActivity.this)
.setTitle("HI")
.setMessage(y);
alt.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alt.show();
}
});
return (view != null) ? view : null;
Here is My ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.a_hamoud.listview_sqlserver.MainActivity"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="8"
>
</ListView>
Please help me to find where the error is.
Thanks.
Try change:
holder.ord_num = (TextView) findViewById(R.id.lblID);
holder.cus_name = (TextView) findViewById(R.id.cus_name);
holder.cus_tel = (TextView) findViewById(R.id.cus_tel);
holder.ord_status = (TextView) findViewById(R.id.ord_status);
to:
holder.ord_num = (TextView) view.findViewById(R.id.lblID);
holder.cus_name = (TextView) view.findViewById(R.id.cus_name);
holder.cus_tel = (TextView) view.findViewById(R.id.cus_tel);
holder.ord_status = (TextView) view.findViewById(R.id.ord_status);
Also remove the +1 in getCount(). Hope that helps!
before set text you must check one codition which is null in your list at first index.
if (ID_ArrayList.get(i) != null){
holder.ord_num.setText("Order ID :" + ID_ArrayList.get(i));
holder.cus_name.setText("Name : " + NAME_ArrayList.get(i));
holder.cus_tel.setText("Telephone No : " + PHONE_NUMBER_ArrayList.get(i));
holder.ord_status.setText("Status : " + STATUS_ArrayList.get(i));
}
i dont know which field is null show you can check.
The adapter thinks it has more items than it really has. Remove the +1 in getCount():
#Override
public int getCount() {
return ID_ArrayList.size();
}
Just update your update your getCount method with this one
#Override
public int getCount() {
return ID_ArrayList.size();
}

Search Filter in the ListView Not Working as Expected

We have a list view fragment that contains a listview, edit text(for search) and check box(Select All). As mentioned we are using Edit Text for searching the values from the list view.
Problem:
We have list view displaying 10 items( list view sorted alphabetically).
When we type 'W' in the edit text we are displayed with two values i.e. WF and WH.
The selection is made for WF(first item displayed).
After clearing the characters in the edit text, we are now displayed with the complete list of the list view.
But the selection is now made for first item in the list AHMD. (we intended to select WF)
Basically, the positions of the data in the list view is not getting refreshed after we have performed search.
code:
public static class ListViewFragment extends Fragment {
private ListView myListView;
private EditText editsearch;
private CheckBox selectAll;
private String SELECTED_FILTER;
private ArrayList<String> SelectedFilter1;
private ArrayList<String> checkekprev=new ArrayList<String>();
private ArrayList<String> CheckedFitlers=new ArrayList<String>();
ArrayAdapter<String> adapter_list;
OnCheckedItemsLister onCheckedItemsLister;
public ListViewFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onCheckedItemsLister = (OnCheckedItemsLister) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement onSomeEventListener");
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
SelectedFilter1=getArguments().getStringArrayList("ArrayList");
SELECTED_FILTER=getArguments().getString("SELECTED_FILTER");
checkekprev=getArguments().getStringArrayList("checkedprevlist");
if(checkekprev.size()==SelectedFilter1.size())
selectAll.setChecked(true);
else
selectAll.setChecked(false);
adapter_list = new ArrayAdapter<String>(this.getActivity(),
android.R.layout.simple_list_item_multiple_choice,SelectedFilter1);
adapter_list.notifyDataSetChanged();
myListView.setAdapter(adapter_list);
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myListView.setTextFilterEnabled(true);
try{
if(checkekprev.isEmpty()==false){
Log.i("Adapter set", "Yes");
for(int j=0;j<checkekprev.size();j++){
Log.i("Adapter set", "Yes:"+j);
int pos=adapter_list.getPosition(checkekprev.get(j));
Log.i("Adapter set", "Pos:"+pos);
myListView.setItemChecked(pos,true);
}
}
}catch(NullPointerException e){
Log.i("Null set", "Yes");
}
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter_list.getFilter().filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
selectAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
Log.i("CheckBOX","Is Checked:"+isChecked);
if(isChecked)
{
for ( int i=0; i< myListView.getCount(); i++ )
myListView.setItemChecked(i, true);
}else
{
for ( int i=0; i< myListView.getCount(); i++ )
myListView.setItemChecked(i, false);
}
SparseBooleanArray checked = myListView.getCheckedItemPositions();
CheckedFitlers.clear();
for(int i=0;i<=checked.size();i++){
if (checked.get(i)){
CheckedFitlers.add(SelectedFilter1.get(i));
}
}
onCheckedItemsLister.someEvent(CheckedFitlers,SELECTED_FILTER);
}
}
);
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id){
setItemChecked(position);
onCheckedItemsLister.someEvent(CheckedFitlers,SELECTED_FILTER);
}
});
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if(savedInstanceState!=null){
checkekprev=savedInstanceState.getStringArrayList("Checked_Values");
}
}
public void setItemChecked(int position){
//if(SelectedFilter1.get(position).)
//int len = myListView.getCount();
SparseBooleanArray checked = myListView.getCheckedItemPositions();
for(int i=0;i<=checked.size();i++){
Log.i("Check Sparse Array","Check Sparse Array: "+checked.get(i));
}
//for (int i = 0; i < len; i++){
Log.i("SelectedFilter1.get(position)","SelectedFilter1.get(position):::"+SelectedFilter1.get(position));
Log.i("checked.get(position))","checked.get(position)):::"+checked.get(position));
for (int i=0; i<CheckedFitlers.size();i++){
Log.i("CheckedFitlers","CheckedFitlers:::" + CheckedFitlers.get(i));
}
for (int i=0; i<checkekprev.size();i++){
Log.i("checkekprev","checkekprev:::" + checkekprev.get(i));
}
Log.i("CheckedFitlers","CheckedFitlers:::" + CheckedFitlers.size());
Log.i("checkekprev","checkekprev:::" + checkekprev.size());
if(CheckedFitlers.size() == 0 && checkekprev.size() != 0){
CheckedFitlers = checkekprev;
}
Log.i("CheckedFitlers","CheckedFitlers:::" + CheckedFitlers.size());
if (checked.get(position)) {
Log.i("Adding","Adding::"+checked.get(position));
CheckedFitlers.add(SelectedFilter1.get(position));
for(int i=0;i<checkekprev.size();i++){
//Log.i("Checked Filters FOr loop","Checked Filters:"+CheckedFitlers.get(i));
}
} else
{
Log.i("Removing","Removing::"+checked.get(position)+":"+SelectedFilter1.get(position));
CheckedFitlers.remove(SelectedFilter1.get(position));
for(int i=0;i<checkekprev.size();i++){
//Log.i("Checked Filters for loop","Checked Filters:"+CheckedFitlers.get(i));
}
}
Log.i("CheckedFitlers","CheckedFitlers:::" + CheckedFitlers.size());
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_list_view, container, false);
myListView=(ListView) rootView.findViewById(R.id.listView_brand);
editsearch = (EditText) rootView.findViewById(R.id.search);
selectAll=(CheckBox) rootView.findViewById(R.id.checkBox1);
selectAll.setFocusable(false);
return rootView;
}
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
Log.i("savedInstanceState in listfragment","savedInstanceState in listfragment");
//onCheckedItemsLister.someEvent(CheckedFitlers,SELECTED_FILTER);
onCheckedItemsLister.getSelectedFilter(SELECTED_FILTER);
}
}
When you typed 'W' in the edit text we are displayed with two values i.e. WF and WH. The selection is made for WF(first item displayed).
But you have performed action for first row of a listview, Now the checkbox of listview is checked and when clearing the characters in the edit text, your are seeing the complete list of the list view with first box checked. which is correct.
If you want to avoid this issues, Create custom adapter and override getfilter method.
Otherwise, Create your own logic and call listView.setItemChecked( stored positions, true/false); in ontextchanged.
In this example, let's say that the activity labels and listview items have equal values. There are 10 items from WF to WZ. (I sampled with 4 items) When "WZ" is typed in the edittext, the "WZ" item is displayed on the first line of the listview. When the first line is clicked, it is desirable to calling the "WZ" activity, not the "WF" activity. I've created the following little code for it, and it works fine.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String v1 = getString(R.string.title_activity_wf).toString();
String v2 = getString(R.string.title_activity_wh).toString();
String v3 = getString(R.string.title_activity_wm).toString();
String v4 = getString(R.string.title_activity_wt).toString();
.
.
.
.
.
.
String selectedFromList = (String) (listView.getItemAtPosition(position));
if (selectedFromList.equalsIgnoreCase(v1)) {
startActivity(new Intent(getApplicationContext(), Wf.class));
} else if (selectedFromList.equalsIgnoreCase(v2)) {
startActivity(new Intent(getApplicationContext(), Wh.class));
} else if (selectedFromList.equalsIgnoreCase(v3)) {
startActivity(new Intent(getApplicationContext(), Wm.class));
} else if (selectedFromList.equalsIgnoreCase(v4)) {
startActivity(new Intent(getApplicationContext(), Wt.class));
}
});

Removing items from ListActivity with custom listadapter containing checkboxes

I am trying to remove the list items from listactivity which has custom list adapter. Custom list adapter has textviews and checkboxes. When user selects the items by clicking on checkboxes, a button appears in the bottom of screen and on clicking on button, i want to delete the items from the adapter. I have implemented the solution by setting the position as a tag to checkbox but its not working. Checked positions and listview indices are not mapped correctly. I am posting my code here:
ListAdapter
<code>
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null)
{
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.gmail_list_layout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.checkView = (CheckBox) view.findViewById(R.id.check);
viewHolder.timeView = (TextView) view.findViewById(R.id.time_content);
viewHolder.fromView = (TextView) view.findViewById(R.id.from_content);
viewHolder.subjectView = (TextView) view.findViewById(R.id.subject_content);
viewHolder.rootLayout = (ViewGroup) view.findViewById(R.id.rootGmail);
Log.i("mustang", "Adding view at Position: " + position);
viewHolder.checkView.setTag(position);
viewHolder.checkView.setOnCheckedChangeListener(checkListener);
view.setTag(viewHolder);
}
OnCheckedChangeListener checkListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Integer position = (Integer)buttonView.getTag();
Log.i("mustang", "Position: " + position);
if(isChecked)
{
checkedPositions.put(position, position);
buttons.put(position, buttonView);
}
else
{
checkedPositions.remove(position);
buttons.remove(position);
}
Log.i("mustang", "Positions Array: " + checkedPositions.size());
ArrayList<Integer> positions = new ArrayList<Integer>(checkedPositions.values());
context.itemsSelected(positions);
}
};
public ArrayList<Integer> getCheckedPositions()
{
return new ArrayList<Integer>(checkedPositions.values());
}
</code>
Whenever checkbox is selected, button appears in bottom to remove the items. Button showing code and removal code is shown here:
Showing button when items selected by checkboxes are more than one:
<code>
public void itemsSelected(ArrayList<Integer> positions)
{
Log.i("mustang", "positions.size(): " + positions.size());
deleteItemsButton.setText("Delete " + positions.size() + " mails?");
deleteItemsButton.setVisibility(positions.size() > 0 ? Button.VISIBLE : Button.INVISIBLE);
}
</code>
And when user clicks on it following code runs:
<code>
private OnClickListener deleteItemsListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<Integer> positions = emails.getCheckedPositions();
for(Integer p : positions)
{
emails.remove(emails.getItem(p.intValue()));
}
emails.notifyDataSetChanged();
}
};
</code>
Please point me out that I am implementing the technique in the right way.
Thanks in advance.

Access to ToggleButtons in ListView

I am using Custom Adapter (ListAdapter.java) that extends ArrayAdapter to fill ListView (List.java).
After that ListView row contains TextView and ToggleButton.
In List.java I can register click on ListView row:
sett_list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, android.view.View view, int position, long id) {
but how can I register click on ToggleButton, and get row position of that button?
EDIT: #MDMalik
In ListAdapter.java:
A):
View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.settings_row, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.option);
final ToggleButton toggle = (ToggleButton) rowView.findViewById(R.id.toggle);
B):
if (values2[position].equals("on")) {
toggle.setChecked(true);
} else {
toggle.setChecked(false);
}
C):
toggle.setTag(Integer.valueOf(position));
toggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), Integer.valueOf(position) + " : Click", Toast.LENGTH_SHORT).show();
}
});
That's it. Now I have position of clicked button. Thank you.
How can I write result to database now?
Something like this (not working):
toggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (toggle.isChecked() == true) {
checked = 1;
myDB = SQLiteDatabase.openOrCreateDatabase("database.db", null);
myDB.execSQL("UPDATE " + TableName + " SET on_off_ = 'on' WHERE sett_ = '" + values[position] + "'");
myDB.close();
} else {
checked = 0;
myDB = SQLiteDatabase.openOrCreateDatabase("database.db", null);
myDB.execSQL("UPDATE " + TableName + " SET on_off_ = 'off' WHERE sett_ = '" + values[position] + "'");
myDB.close();
}
}
});
A) As you have a CustomAdapter, you need to intalize your ToggelButton in getView.
B) Your String array should have a default value for that button, either true or false that can be achieve something like this
String chkCondition = hmap.get("chk").toString().toLowerCase();
Boolean blnChk = true;
if (chkCondition.equals("false"))
{ blnChk = false; }
chkBox.setChecked(blnChk);
C) Then you need to declare onClickListener for that where is basically reintallize your origianl array finding your TextView value and the new chk value.
private void setCheckValue(String Condition, String upc) {
for (int i = 0; i < data.size(); i++) {
String Upccode = data.get(i).get("UpcCode").toString();
if (Upccode.equals(upc)) {
HashMap<String, String> hmap = new HashMap<String, String>();
hmap = data.get(i);
hmap.put("chk", Condition);
data.set(i, hmap);
break;
}
}
}
D) Returning the modified data to the Activity by declaring a method call getData()
public ArrayList<HashMap<String, String>> getData() {
return data;
}
I use data in my CustomAdapter. Data is a ArrayList<HashMap<String, String>> .
Edit I don't do SQL command on toggle change. I collect them in a array. Then you obviously have a Submit button in your Activity. Once you press the submit button. I get the Data from the CustomAdapter. Which is done by getData() this will give you HashMap in your Activity.
I tend to achieve this by setting usual listeners inside Adapter when inflating View in getView and also remembering position for that View inside tag.
Take a look at this working example: ButtonsProblemsExampleActivity.java.

Android: Get the listview item from button clicked in custom listview

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();
}

Categories

Resources