Android: ListView with Search functionality and checkBox - android

I have implemented a listView with search functionality and checkBox. The problem is once I search from editText,once searched text is selected its taking the value from original listView and I am not getting the exact value what I want.
I found some solutions online but did not work. Please help me.
activity_invitecaretaker.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:dividerHeight="1dp"
android:layout_below="#+id/inputSearch"
android:layout_above="#+id/button_invite">
</ListView>
<EditText android:id="#+id/inputSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/search_caretaker"
android:inputType="text"
android:maxLines="1"
style="#style/EditTextCustomHolo"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
<Button android:id="#+id/cancel_text"
android:text="#string/cancel_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignBottom="#+id/inputSearch"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/send_invite"
android:id="#+id/button_invite"
android:gravity="center"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignBottom="#android:id/android:list" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/skip_button"
android:id="#+id/button_skip"
android:gravity="center"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignBottom="#android:id/android:list" />
</RelativeLayout>
list_example_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<CheckedTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/email_entry"/>
<CheckedTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/phone_entry"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox_listview"
android:layout_gravity="end"
android:layout_alignParentRight="true"/>
</RelativeLayout>
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by on 2015-10-15.
*/
public class InviteCaretakers extends Activity implements AdapterView.OnItemClickListener {
private EditText inputSearch;
private ArrayAdapter<String> adapter;
private EditText edit;
private Button skipButton;
private Button inviteButton;
private Button cancelButton;
private Boolean test;
private String email;
private CheckBox cb;
private ListView lv ;
private TextView emailId;
private String emailOrg;
private String searchStr;
ArrayList<StringBuilder> checkedList;
private ArrayList<String> arraySort= new ArrayList<String>();
private ArrayList<String> checkedcontacts;
private MyAdapter ma ;
private int EL_Length;
ArrayList<String> emailList = new ArrayList<String>();
private LayoutInflater inflater;
final DeviceUtil deviceUtil=new DeviceUtil();
final String TAG = InviteCaretakers.class.getName();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_invitecaretaker);
inputSearch = (EditText) findViewById(R.id.inputSearch);
searchStr = inputSearch.getText().toString();
skipButton = (Button) findViewById(R.id.button_skip);
skipButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent RemindInviteIntent = new Intent(getApplicationContext(), RemindInvite.class);
startActivity(RemindInviteIntent);
}
});
getEmailContact();
lv = (ListView) findViewById(R.id.list);
doSearch();
adapter = new ArrayAdapter<String>(this, R.layout.list_example_entry, R.id.email_entry, emailList);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)skipButton.getLayoutParams();
skipButton.getLayoutParams().width = (int) (deviceUtil.getScreenWidth(getApplicationContext())) * 53 / 100;
skipButton.setLayoutParams(params);
inviteButton = (Button) findViewById(R.id.button_invite);
RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams)inviteButton.getLayoutParams();
inviteButton.getLayoutParams().width = (int) (deviceUtil.getScreenWidth(getApplicationContext())) / 2;
inviteButton.setLayoutParams(params1);
//if checked status is true add to array thats-it
checkedcontacts = new ArrayList<String>();
System.out.println("no of checked boxes..." + ma.mCheckStates.size());
System.out.println("FINALOUT checkedlist EMAILList" + checkedcontacts);
int count = checkedcontacts.size();
Toast.makeText(getBaseContext(), "You have selected" + String.valueOf(ma.mCheckStates.size()) + "contacts!!!", Toast.LENGTH_SHORT).show();
//onclick of invite button- get count & value of radio
inviteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//StringBuilder checkedcontacts = new StringBuilder();
checkedcontacts = new ArrayList<String>();
System.out.println("no of checked boxes..." + ma.mCheckStates.size());
if ( ma.mCheckStates.size() != 0) {
for (int i = 0; i < emailList.size(); i++) {
test = ma.mCheckStates.get(i);
System.out.println("test......" + test);
if (test == true){
checkedcontacts.add(emailList.get(i).toString());
String email= emailList.get(i).toString();
System.out.println("Checked......" + emailList.get(i).toString());
getEmail();
checkedcontacts.addAll(arraySort);
adapter.notifyDataSetChanged();
}
}
}
//
}
});
//onclick of invite button- get count & value of radio
cancelButton = (Button)findViewById(R.id.cancel_text);
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
inputSearch.setText("");
}
});
} //oncreate
public void getEmail(){
System.out.println("FINAL-OUT CHECKED ARRAY" + checkedcontacts);
int count = checkedcontacts.size();
System.out.println("count"+count);
for (int j = 0; j < checkedcontacts.size(); j++) {
email= checkedcontacts.get(j).toString();
System.out.println("email inString" + email);
//if (!email.isEmpty()){
Pack pack = PackManager.getInstance(getApplicationContext()).activePack();
System.out.println("pack in inviteCare"+pack);
PackManager.getInstance(getApplicationContext()).inviteCareTakers(pack, email, new OnServerResponseListener<String, String>() {
#Override
public void onSuccess(String successParam) {
PackManager.getInstance(InviteCaretakers.this);
Intent intent = new Intent().setClass(InviteCaretakers.this, com.synclabs.dogsync.members.InviteSent.class);
InviteCaretakers.this.startActivity(intent);
Log.d(TAG, "SUCCESS inside inviteCareTakers");
getEmail();
for (int j = 1; j < checkedcontacts.size(); j++) {
email = checkedcontacts.get(j).toString();
System.out.println("email inside onSuccess" + email);
}
getEmail();
//finish();
}
#Override
public void onFailure(String failureParam) {
Log.d(TAG, "failure inside inviteCareTakers");
}
});
} // for
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
//from device contacts extract email Id's
public ArrayList<String> getEmailContact() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor cur1 = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (cur1.moveToNext()) {
String email = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("Email INVITE", email);
//check if emailList already contains, if not there then add else don't add to list
if (!emailList.contains(email)) {
emailList.add(email);
}
}
cur1.close();
}
Log.e("EmailList INVITE1", String.valueOf(emailList));
EL_Length = emailList.size();
Log.e("length of arrayList", String.valueOf(EL_Length));
adapter = new ArrayAdapter<String>(this, R.layout.list_example_entry, R.id.email_entry, emailList);
}
return emailList;
}
public void addToList() {
edit = (EditText) findViewById(R.id.inputSearch);
if (edit != null ) {
emailList.add(edit.getText().toString());
adapter.notifyDataSetChanged();
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactID = ops.size();
// Adding insert operation to operations list
// to insert a new raw contact in the table ContactsContract.RawContacts
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build());
// Adding insert operation to operations list
// to insert Home Email in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, edit.getText().toString())
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_HOME)
.build());
try {
// Executing all the insert operations as a single database transaction
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Toast.makeText(getBaseContext(), "Contact is successfully added", Toast.LENGTH_SHORT).show();
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
}
public void doSearch() {
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
inputSearch = (EditText) findViewById(R.id.inputSearch);
searchStr = inputSearch.getText().toString();
System.out.println("searchStr inside onTextChanged"+ searchStr);
arraySort.clear();
int textlength = inputSearch.getText().length();
for (int i = 0; i < emailList.size(); i++) {
if (textlength <= emailList.get(i).length()) {
if (inputSearch.getText().toString().equalsIgnoreCase
((String) emailList.get(i).subSequence(0, textlength))) {
//get the index of value in new array_sort and store it in a variable for check
System.out.println("EmailList index" + emailList.indexOf(emailList.get(i).toString()));
emailOrg = emailList.get(i).toString();
System.out.println("emailOrg" + emailOrg);
arraySort.add(emailOrg);
}
}
}
//this is needed for searching through
adapter = new ArrayAdapter<String>(InviteCaretakers.this, R.layout.list_example_entry, R.id.email_entry, emailList);
lv.setAdapter(adapter);
adapter.getFilter().filter(s.toString());
adapter.notifyDataSetChanged();
//
// not existing = add to array and list call if it matches email id structure
Validation va = new Validation();
if (va.isValidEmailId(searchStr)) {
getEmailContact();
addToList();
Log.e("length EL AFTER ADDING", String.valueOf(EL_Length));
}
System.out.println("array_sort items" + arraySort);
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
//
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(emailList.size());
mInflater = (LayoutInflater)InviteCaretakers.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return emailList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#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
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.list_example_entry, null);
TextView tv= (TextView) vi.findViewById(R.id.email_entry);
cb = (CheckBox) vi.findViewById(R.id.checkBox_listview);
tv.setText(emailList.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}

Related

How to get value from listview checkbox?

I am having a little trouble with listview, I want to get values of listview whose checkbox are selected when button is clicked. till now i have created a listview with checkboxes and fetched all the values from mysql but i am not able to get values of listview which are checked.
This is my class
public class ListViewMultipleSelectionActivity extends Activity{
Button button;
String myJSON;
private static final String TAG_NAME = "cat_name";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
personList = new ArrayList<HashMap<String,String>>();
list1 = (ListView) findViewById(R.id.list);
button = (Button)findViewById(R.id.testbutton);
getlat();
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void getlat(){
class GetDataJSON extends AsyncTask<String, Void, String> {
public void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
String result = null;
try {
URL url = new URL("http://xxxxxxxxxxxx/category.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder("");
String line="";
while ((line = in.readLine()) != null)
{
sb.append(line).append("\n");
}
result = sb.toString();
}
assert inputStream != null;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line).append("\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "["+result+"]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList(){
try {
peoples = new JSONArray(myJSON);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name = c.getString(TAG_NAME);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
ListViewMultipleSelectionActivity.this, personList, R.layout.result,
new String[]{TAG_NAME},
new int[]{R.id.name}
);
list1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list1.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/testbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Submit" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/testbutton"
android:layout_alignParentTop="true"/>
</RelativeLayout>
result.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/cbBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" >
</CheckBox>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:orientation="vertical"
android:layout_weight="1" >
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textStyle="bold"/>
</LinearLayout>
</LinearLayout>
i have implemented this on testbutton(Button) click please check
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = list1.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
selectedItems.add((String) adapter.getItem(position));
}
String[] valuess = new String[selectedItems.size()];
for (int i = 0; i < selectedItems.size(); i++) {
valuess[i] = selectedItems.get(i);
}
Toast.makeText(ListViewMultipleSelectionActivity.this, String.valueOf(valuess), Toast.LENGTH_SHORT).show();
}
});
this is i am getting after click
E/-->>>>: [Ljava.lang.String;#ca01299
What you can do is creating a custom class to store these values along with a custom adapter that supports it. So whenever you click the button you can call the given function to retrieve the statuses of those items. Example architecture given below:
PS: Since I don't know what you want to do with checked values, I left you there with comments which you can change with your need.
MainActivity.java
package com.rencsaridogan.stackoverflow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<ExampleClass> objects;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
objects = new ArrayList<>();
for (int i = 0; i < 10; i++){
objects.add(new ExampleClass("Example Name " + i));
}
final ListView listView = (ListView) findViewById(R.id.listView);
final Button testButton = (Button) findViewById(R.id.testButton);
final ExampleAdapter exampleAdapter = new ExampleAdapter(this, R.layout.list_cell, objects);
listView.setAdapter(exampleAdapter);
exampleAdapter.notifyDataSetChanged();
testButton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
getCheckedItems();
}
});
}
private void getCheckedItems(){
for (int i = 0; i < 10; i++) {
if (objects.get(i).isChecked()){
Log.i("MainActivity",i + " is checked");
/**
* Value is checked, do what you need to do here
*/
} else {
Log.i("MainActivity",i + " is NOT checked");
/**
* Value is NOT checked
*/
}
}
}
}
ExampleAdapter.java
package com.rencsaridogan.stackoverflow;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by rencsaridogan on 16/02/2017.
*/
public class ExampleAdapter extends ArrayAdapter<ExampleClass> {
ArrayList<ExampleClass> objects;
Listener listener;
Context context;
public ExampleAdapter(Context context, int resource, ArrayList<ExampleClass> objects) {
super(context, resource);
this.context = context;
this.objects = objects;
}
#Override public int getViewTypeCount() {
return super.getViewTypeCount();
}
#Override public int getCount() {
return objects.size();
}
#SuppressLint("InflateParams") #Override public View getView(int position, View convertView, #NonNull ViewGroup parent) {
if (convertView == null){
Log.i("ExampleAdapter","ConvertView inflated");
convertView = LayoutInflater.from(context).inflate(R.layout.list_cell, null, false);
}
Log.i("ExampleAdapter","Setting of values");
final ExampleClass data = objects.get(position);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.textView = (TextView) convertView.findViewById(R.id.textView);
viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
viewHolder.textView.setText(data.getName());
viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
data.setChecked(isChecked);
}
});
return convertView;
}
public void setListener(Listener listener) {
this.listener = listener;
}
private class ViewHolder {
TextView textView;
CheckBox checkBox;
}
public ArrayList<ExampleClass> getObjects() {
return objects;
}
public void setObjects(ArrayList<ExampleClass> objects) {
this.objects = objects;
notifyDataSetChanged();
}
#Override public long getItemId(int position) {
return super.getItemId(position);
}
public interface Listener {
void onCheckedChanged(int position);
}
}
ExampleClass.java
package com.rencsaridogan.stackoverflow;
/**
* Created by rencsaridogan on 16/02/2017.
*/
public class ExampleClass {
String name;
boolean isChecked;
public ExampleClass(String name) {
this.name = name;
}
public ExampleClass(String name, boolean isChecked) {
this.name = name;
this.isChecked = isChecked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
}
Set checkbox object as tag to your row view that might be your 'convertView' in getView() method of your adapter.
Write on click listener on your row view.
3.Inside that click-listener to row view getTag from view that's parameter in onClick method and cast it to checkbox and then setChecked to true for that checkbox object.
code might look like this,
convertView.setTag(yourCheckBoxObject);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v.getTag();
cb.setChecked(true);
}
});
Please refer this sight for more information Getting an issue while checking the dynamically generated checkbox through list view
In your Adapter there was one #override method called getView() in that method you will get the current item which you will clicked
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox checkBox=(CheckBox) view;
String tagName="";
if(checkBox.isChecked()){
tagName=checkBox.getTag().toString();
deleteServices.add(tagName);
checkboxArrayList.add(checkBox);
}else {
checkboxArrayList.remove(checkBox);
tagName=checkBox.getTag().toString();
if(deleteServices.size()>0&&deleteServices.contains(tagName)){
deleteServices.remove(tagName);
}
});

contact on list view with select all option and search option on android

contact on list view with select all option and search option on android
i have tried a lot of ways but no matter to find a list view with name,phone no and check box for everyone and also a select all button and search option
public void onTextChanged(CharSequence s,int start, int before, int count)
{
textlength = et.getText().length();
// et.setText(textlength);
if(et.getText().toString().equalsIgnoreCase("helloo")){
// Toast.makeText(getApplicationContext(),"jd",1000).show();
for (int i = 0; i < name1.size(); i++)
{
if (textlength <= name1.size())
{
Toast.makeText(getApplicationContext(),"searching.....inside",1000).show();
if(et.getText().toString().equalsIgnoreCase((String)((CharSequence) name1).subSequence(0,textlength)))
{
// array_sort.addAll(name1);
}
}
if(et.getText().toString().equalsIgnoreCase(
(String)(CharSequence) name1)){
Toast.makeText(getApplicationContext(),"searching.....",1000).show();
}
}
lv.setAdapter(new ArrayAdapter<String>
(contact_fetch.this,
android.R.layout.simple_list_item_1, array_sort));
}
}
});
I had the same problem.Finally I solved with this code. Hope It will help you :)
//layout function
public void lay_out(List<String> exp1,int k){
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
container.removeAllViews();
for(int i=0;i<exp1.size();i++){
final View addView = layoutInflater.inflate(R.layout.row, null);
TextView tv=(TextView)addView.findViewById(R.id.textView1);
final CheckBox cb=(CheckBox) addView.findViewById(R.id.checkbox1);
if(k==0)
{
cb.setChecked(false);
}
else
{
cb.setChecked(true);
}
tv.setText(name1.get(i));
cb.setText(phno1.get(i));
container.addView(addView);
cb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(),cb.getText().toString(),10).show();
if(cb.isChecked()==true){
if(checkedcontacts.length()<0)
{
for(int i=0;i<=checkedcontacts.length();i++)
{
if(!checkedcontacts.equals(cb.getText().toString()))
{
// insertion
checkedcontacts.append(cb.getText().toString());
checkedcontacts.append("\n");
}
}
}
else{
checkedcontacts.append(cb.getText().toString());
checkedcontacts.append("\n");
}
}
else if(cb.isChecked()==false){
s_all.setChecked(false);
try{
Toast.makeText(getApplicationContext(),cb.getText().toString(),10).show();
//Pattern.compile(cb.getText().toString()).matcher(checkedcontacts).replaceAll("");
checkedcontacts.delete(checkedcontacts.indexOf(cb.getText().toString()),
cb.getText().toString().length());
}
catch(Exception e){
System.out.println("error on array"+e);
}
}
}
});
container.setVisibility(View.VISIBLE);
}
}
Try this code to get all contacts with checkboxex:
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Display extends Activity implements OnItemClickListener {
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
MyAdapter ma;
Button select;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
getAllContacts(this.getContentResolver());
ListView lv = (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder checkedcontacts = new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for (int i = 0; i < name1.size(); i++)
{
if (ma.mCheckStates.get(i) == true) {
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
} else {
System.out.println("Not Checked......"
+ name1.get(i).toString());
}
}
Toast.makeText(Display.this, checkedcontacts, 1000).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................." + phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
MyAdapter() {
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater) Display.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#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
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.row, null);
TextView tv = (TextView) vi.findViewById(R.id.contact_name);
tv1 = (TextView) vi.findViewById(R.id.phone_number);
cb = (CheckBox) vi.findViewById(R.id.checkBox_id);
tv.setText("Name :" + name1.get(position));
tv1.setText("Phone No :" + phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
dispay.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:id="#+id/lv"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Select" />
</RelativeLayout>
Row.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/contact_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="John Doe"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/phone_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/contact_name"
android:text="(999)999-9999"
android:textAppearance="?android:attr/textAppearanceMedium" />
<CheckBox
android:id="#+id/checkBox_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
</RelativeLayout>

Assinging the values of cursor to object

I'm working on showing list of contacts with checkbox. I tried implementing my own cursor adapter and it is checkable. But once I check that value I want the contacts to be stored in ContactPerson object. But when I tried it is showing null pointer exception(That's why I commented out that code). My CursorAdapter code goes like this.
ContactListAcitivity.java
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class ContactListActivity extends Activity {
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
list = (ListView) findViewById(R.id.ListView2);
Cursor cur= getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,null,null,null);
startManagingCursor(cur);
String[] result=new String[cur.getCount()];
for (boolean hasData = cur.moveToFirst(); hasData; hasData = cur.moveToNext())
{
ContactPerson contact = new ContactPerson(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)), String.valueOf(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
stopManagingCursor(cur);
list.setAdapter(new contactAdapter(getApplicationContext(), cur));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.contact_list, menu);
return true;
}
private class ViewHolder{
TextView ContactName;
CheckBox contactCheck;
}
class contactAdapter extends CursorAdapter{
private Cursor cursor;
private Context ccontext;
private LayoutInflater inflater;
public contactAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
cursor = c;
ccontext = context;
inflater = LayoutInflater.from(context);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void bindView(View view, Context arg1, Cursor arg2) {
// TODO Auto-generated method stub
ViewHolder holder = (ViewHolder) view.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.ContactName = (TextView) view.findViewById(R.id.contact_name);
holder.contactCheck = (CheckBox) view.findViewById(R.id.contact_check);
view.setTag(holder);
holder.contactCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
cb.setSelected(true);
// ContactPerson contact = (ContactPerson) cb.getTag(); this is the place where it is showing null pointer exception
// Log.i("clicked users", contact.getName());
// contact.setSelected(true);
}
});
}else{
holder = (ViewHolder) view.getTag();
}
// ContactPerson contacts = contactList.get(position);
holder.ContactName.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
// holder.contactCheck.setChecked(contacts.isSelected());
// holder.contactCheck.setTag(contacts);
// holder.ContactName.setText(contacts.getName());
}
#Override
public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.checkbox_item, arg2, false);
}
}
}
activity_contact_list.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">
<ListView
android:id="#+id/ListView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".GroupContactsActivity"
android:layout_alignParentTop="true"
/>
<Button
android:id="#+id/selected_done_1"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:textColor="#FFFFFF"
android:text="Done" />
</RelativeLayout>
checkbox_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip"
android:background="#000000">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/contact_name"
android:layout_alignParentLeft="true"
android:text="textview"
android:textSize="15sp"
android:textColor="#FFFFFF"
android:gravity="center_horizontal"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_alignParentRight="true"
android:layout_weight="1"
android:id="#+id/contact_check"/>
</RelativeLayout>
Can anyone please suggest me how to use that Contact person class in this adapter.
public class ContactPerson {
String name= null, number = null;
boolean Selected = false;
public ContactPerson(String PersonName, String PhoneNumber){
this.name = PersonName;
this.number= PhoneNumber;
}
public String getName(){
return name;
}
public boolean isSelected(){
return Selected;
}
public void setSelected(boolean selected){
this.Selected = selected;
}
public String getPhoneNumber(){
return number;
}
}
Check this code. It worked for me. Best of luck.
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ContactListActivity extends Activity {
ListView list;
ArrayList<ContactPerson> selectedList;
Set<String> phoneID= new TreeSet<String>();;
Button doneButton;
CheckBox cb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
selectedList = new ArrayList<ContactPerson>();
list = (ListView) findViewById(R.id.ListView2);
doneButton = (Button) findViewById(R.id.selected_done_1);
Cursor cur= getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,null);
list.setAdapter(new contactAdapter(getApplicationContext(), cur));
doneButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (String ids : phoneID) {
Log.d("PhoneIds", ids);
Cursor cursorPhoneNumber = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{ids},
null);
Log.d("Number cursor", String.valueOf(cursorPhoneNumber.getCount()));
if (cursorPhoneNumber.moveToFirst()) {
// phoneNumber = cursorPhoneNumber.getString(cursorPhoneNumber.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d("Phone number", cursorPhoneNumber.getString(cursorPhoneNumber.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
cursorPhoneNumber.close();
Cursor cursorName = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{ids},
null);
Log.d("Name cursor", String.valueOf(cursorName.getCount()));
if (cursorName.moveToFirst()) {
Log.d("Phone number", cursorName.getString(cursorName.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY)));
// Name = cursorName.getString(cursorName.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY));
}
cursorName.close();
// selectedList.add(new ContactPerson(Name,phoneNumber));
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.contact_list, menu);
return true;
}
private class ViewHolder{
TextView ContactName;
CheckBox contactCheck;
}
class contactAdapter extends CursorAdapter{
String Name, phoneNumber;
private Cursor cursor;
private Context ccontext;
private LayoutInflater inflater;
public contactAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
cursor = c;
ccontext = context;
inflater = LayoutInflater.from(context);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void bindView(View view, Context arg1, Cursor arg2) {
// TODO Auto-generated method stub
ViewHolder holder = (ViewHolder) view.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.ContactName = (TextView) view.findViewById(R.id.contact_name);
holder.contactCheck = (CheckBox) view.findViewById(R.id.contact_check);
view.setTag(holder);
holder.contactCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cb = (CheckBox) v;
cb.setChecked(cb.isChecked());
// ContactPerson selected = (ContactPerson)cb.getTag();
Log.d("selcted", cb.getTag().toString());
if(cb.isChecked()){
phoneID.add(cb.getTag().toString());
}
}
});
}else{
holder = (ViewHolder) view.getTag();
}
holder.ContactName.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
holder.contactCheck.setTag(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)));
holder.contactCheck.setChecked(false);
}
#Override
public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.checkbox_item, arg2, false);
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
// Log.d("don't know", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
return super.getView(arg0, arg1, arg2);
}
}
}
Here i changed little bit code of your adapter and activity. just look at it:
public class MainActivity extends Activity {
private ArrayList<ContactPerson> arr;
private Context context;
private ListView list;
private ContactArrayAdapter adapter;
private String strName,strNumber;
private View view;
public static boolean[] arrBoolean = null;
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.activity_main);
ProgressDialog pd = new ProgressDialog(this);
list = (ListView)findViewById(R.id.ListView2);
arr = new ArrayList<ContactPerson>();
context = MainActivity.this;
arr = displayContacts();
adapter = new ContactArrayAdapter(this, R.layout.checkbox_item, arr);
list.setAdapter(adapter);
}
public ArrayList<ContactPerson> displayContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
ContactPerson contact;
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
contact = new ContactPerson();
String id = cur.getString(cur.getColumnIndex(People._ID));
String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
ContactPerson cp = new ContactPerson();
cp.setName(name);
cp.setNumber(id);
cp.setSelected(false);
arr.add(cp);
}
}
return arr;
}
//********* Adapter *****
public class ContactArrayAdapter extends ArrayAdapter<ContactPerson> {
// private final List<Contact> list;
private Context context;
private LayoutInflater mInflater;
private List<ContactPerson> list;
public ContactArrayAdapter(Context context, int textViewResourceId,
ArrayList<ContactPerson> stateList) {
super(context, textViewResourceId, stateList);
this.list = new ArrayList<ContactPerson>();
this.list.addAll(stateList);
}
class ViewHolder {
TextView text;
CheckBox checkbox;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder viewHolder = null;
if (view == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.checkbox_item, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.contact_name);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.contact_check);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
final int pos = position;
ContactPerson cp = list.get(position);
viewHolder.text.setText(cp.getName());
viewHolder.checkbox.setChecked(cp.isSelected());
viewHolder.checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) arg0 ;
list.get(pos).setSelected(cb.isChecked());
System.out.println(cb.isChecked());
System.out.println(list.get(pos).getName());
}
});
//viewHolder.text.setTag(cp);
return view;
}
}
}

How to make search listview android?

public class kuliner extends ListActivity {
private static String url = "http://kulinermalang.zz.mu/kuliner/daftar_kuliner.php";
private static final String no_id = "id";
private static final String gambar = "gambar";
private static final String nama = "nama_toko";
JSONArray menu = null;
ListView list;
ArrayList<HashMap<String, String>> daftar_kuliner = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main_listview);
EditText search = (EditText) findViewById(R.id.tfCari);
//ambil();
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
loadingData loading = new loadingData();
loading.execute();
}
//this method for call data to listView
private class loadingData extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog;
String response;
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(kuliner.this);
Dialog.setMessage("Loading Data...");
Dialog.show();
}
#Override
protected String doInBackground(String... urls) {
response = "Success";
return response;
}
#Override
protected void onPostExecute(String result) {
if (response.equalsIgnoreCase("Success")) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
String id_nama;
String gambar_toko = null;
String nama_toko;
String image_url;
try {
menu = json.getJSONArray("daftar");
for (int i = 0; i < menu.length(); i++) {
JSONObject ar = menu.getJSONObject(i);
id_nama = ar.getString(no_id);
gambar_toko = ar.getString(gambar);
nama_toko = ar.getString(nama);
HashMap<String, String> map = new HashMap<String, String>();
map.put(no_id, id_nama);
map.put(gambar, gambar_toko);
map.put(nama, nama_toko);
daftar_kuliner.add(map);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Dialog.dismiss();
}
}
}
You could probably do something like this
//get your ListView with attached SimpleAdapter
ListAdapter adapter = listView.getAdapter();
for(int i = 0; i < adapter.getCount(); i++) {
String value = ((HashMap<String, String>)adapter.getItem(i)).get("Your_key");
}
But i'm not sure i understand the question correctly, what is it that you want to accomplish exactly? I'm sorry for asking a question here but i'm not allowed to comment yet :/
in the onTextChangedMethod of TextWatcher, write an if condition that - the edittext values is in the list you are inflating in your listview, if yes them add that edittext value to another list and set that list to your adapter. For Example Here is my Code :- ( Just focus on ListView, ArrayList and TextWatcher. Dont mind other code)
package com.example.alaramsms;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ContactActivity extends Activity implements OnItemClickListener{
String textlength;
ArrayList<String> filtered_name;
ArrayList<String> filtered_phone;
ArrayList<String> name1 = new ArrayList<String>();
ArrayList<String> phno1 = new ArrayList<String>();
ArrayList<String> phno0 = new ArrayList<String>();
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> mOriginalValues;
MyAdapter mAdapter ;
Button send,btnselect;
ListView lv;
EditText myFilter;
boolean flag = false;
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get);
lv =(ListView)findViewById(R.id.lv);
getAllCallLogs(this.getContentResolver());
mAdapter = new MyAdapter(this,name1,phno1);
lv.setAdapter(mAdapter);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
send = (Button) findViewById(R.id.button1);
CheckBox chkAll = ( CheckBox ) findViewById(R.id.chkAll);
chkAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
flag = !flag;
mAdapter.notifyDataSetChanged();
}
});
myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
#SuppressLint("DefaultLocale")
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
textlength = myFilter.getText().toString();
filtered_name = new ArrayList<String>();
filtered_phone = new ArrayList<String>();
for (int i = 0; i < name1.size(); i++)
{
if(name1.get(i).toString().toUpperCase().contains(myFilter.getText().toString().toUpperCase()))
{
System.err.println("Selection: " + textlength);
filtered_name.add(name1.get(i));
filtered_phone.add(phno1.get(i));
}
}
mAdapter = new MyAdapter(ContactActivity.this,filtered_name,filtered_phone);
lv.setAdapter(mAdapter); // Here inflating two other lists containing he searched items
}
});
send.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............."+mAdapter.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(mAdapter.mCheckStates.get(i)==true)
{
phno0.add(phno1.get(i).toString()) ;
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("..Not Checked......"+name1.get(i).toString());
}
}
Toast.makeText(ContactActivity.this, checkedcontacts,1000).show();
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("name",phno0);
setResult(RESULT_OK,returnIntent);
finish();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
mAdapter.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................."+phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{
private SparseBooleanArray mCheckStates;
ArrayList<String> name1;
ArrayList<String> phno1;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter(ContactActivity contactActivity, ArrayList<String> name1, ArrayList<String> phno1)
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)ContactActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.name1 = name1;
this.phno1 = phno1;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#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
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(flag); // You just have to add this line
cb.setOnCheckedChangeListener(this);
return vi;
}
/*
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
//ArrayList<String> name1 = new ArrayList<String>();
arrayList = (ArrayList<String>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<String> FilteredArrList = new ArrayList<String>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<String>(name1); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
/* if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
String name1 = mOriginalValues.get(i).toString();
if (name1.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(name1);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}*/
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}

Click Event Listeners in a ListActivity [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android: How to fire onListItemClick in Listactivity with buttons in list?
i have develop one app in which i have make ListActivity in which custome listview are going to display custom item list.all things are going to well but here i am confuse with itemOnClickListner. how can i add onclick listner in listActivity ? because there are not any listview that initialize and i can set listner trough that listview control... i have find out from here but its also not working for me
:Here is Code ::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends ListActivity implements OnClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
Update::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends ListActivity implements OnClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> implements OnClickListener {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"hey this ", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Click this");
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
Update3
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends Activity implements OnClickListener, OnItemClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites);
lstFavrowlistv = (ListView)findViewById(R.id.lstFavrowlistv);
lstFavrowlistv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
});
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
lstFavrowlistv.setAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) lstFavrowlistv.getAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> implements OnClickListener {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"hey this ", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Click this");
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
use getListview() in list Activity to get List..........
in Oncreate
ListView lv = getListView();
http://www.mkyong.com/android/android-listview-example/
this link has both ways
1- overriding onListItemClick(
2- Setting you listener..
Try this way..
ListView lv = getListView();
lv. storelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
}
this are help you.
Thanks
Override the function onlistitemclick() for this. Here the integer position represents the postion of item that you had pressed
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
.......
}
Try this one
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
}
});

Categories

Resources