i am new in android.i make a simple maths apps.
i use the check box for select right option but problem is here the answer option is not only one but also two,three means multi select so i use the check box
chkOption.setOnCheckedChangeListener(this);
event and try to handle this.and store the select value in one Arraylist.but when i select option the value is add in arrayList but when i do uncheck(Diselect) then also the event is occur and the value add in arraylist.
my code is below
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
CheckBox chk=(CheckBox) buttonView;
if(chk.isChecked())
{
forMetchCheckBox.add(String.valueOf(chk.getText()));
}
}
forMetchCheckbow is my String ArrayList .So i can what to do?
How to Handle this problem.
if any user deselect the option then the checkbox select value is remove from ArrayList.it`s possible?
It seems you are having more than one checkbox and you are setting global listener for every checkbox. So, in that case you need to identify the event for specific checkbox also.
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
int id = buttonView.getId();
if(id == R.id.chk)
{
if(chk.isChecked()){
forMetchCheckBox.add(String.valueOf(chk.getText()));
}
else{
forMetchCheckBox.remove(String.valueOf(chk.getText()));
}
}
else if(id == R.id.chk1){
....
}
}
and so on, that will make your listener work perfect.
What's wrong is your if condition. It should be:
if( isChecked )
and not
if( chk.isChecked() )
chk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
chetimeslot = (String)chk.getTag();
checkbox_timeslot.add(chetimeslot);
}
else{
chetimeslot = (String)chk.getTag();
checkbox_timeslot.remove(chetimeslot);
}
});
To Select Maximum 5 Checkbox at one Time or Count selected and unselected checkbox in Custom listview with CheckBox
package com.test;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ListViewCheckboxesActivity extends ListActivity {
AlertDialog alertdialog = null;
int i1, i2, i3 = 0;
Country rowcheck;
MyCustomAdapter dataAdapter = null;
ListView listView = null;
int k = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fmain);
// Generate list View from ArrayList
displayListView();
checkButtonClick();
}
private void displayListView() {
// Array list of countries Equipments
ArrayList<Country> rowcheckList = new ArrayList<Country>();
Country rowcheck = new Country("", "Hex Bolts", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Hex Cap Screw", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Round Head Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Slotted Head Hex Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Socket Cap Screw", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Sockets", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Square Head Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Carriage Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Plow Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Struts Clamp", false);
rowcheckList.add(rowcheck);
listView = getListView();
dataAdapter = new MyCustomAdapter(this, R.layout.rowcheck_info,
rowcheckList);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country rowcheck = (Country) parent.getItemAtPosition(position);
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> rowcheckList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> rowcheckList) {
super(context, textViewResourceId, rowcheckList);
this.rowcheckList = new ArrayList<Country>();
this.rowcheckList.addAll(rowcheckList);
}
private class ViewHolder {
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.rowcheck_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v ;
Country rowcheck = (Country) cb.getTag();
//To check maximum 5 Selection
if(k>5)
{
if(!cb.isChecked())
{
rowcheck.selected=true;
System.out.println(k--);
}
else
{
System.out.println("if block in-----");
cb.setChecked(false);
Toast.makeText(getApplicationContext(), "Maximum Selection", Toast.LENGTH_LONG).show();
}
}
else
{
System.out.println("else block in-----");
if(!cb.isChecked())
{
rowcheck.selected=true;
System.out.println(k--);
}
else if(cb.isChecked())
{
rowcheck.selected=false;
System.out.println(k++);
}
}
Toast.makeText(getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show()
rowcheck.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Country rowcheck = rowcheckList.get(position);
// holder.code.setText(" (" + rowcheck.getCode() + ")");
holder.code.setText(rowcheck.getName());
// holder.name.setText(rowcheck.getName());
holder.name.setChecked(rowcheck.isSelected());
holder.name.setTag(rowcheck);
return convertView;
}
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
ArrayList<Country> rowcheckList = dataAdapter.rowcheckList;
System.out.println("Size" + rowcheckList.size());
int j = 0;
ArrayList<String> stt = new ArrayList<String>();
for (int i = 0; i < rowcheckList.size(); i++) {
Country rowcheck = rowcheckList.get(i);
// System.out.println(rowcheck.getName());
if (rowcheck.isSelected()) {
stt.add(rowcheck.getName());
// Country.st=new ArrayList<String>();
String s = rowcheck.getName();
System.out.println("String--" + rowcheck.getName());
Country.st.add(s);
j = j++;
System.out.println(j++);
responseText.append("\n" + rowcheck.getName());
}
}
for (int i = 0; i < stt.size(); i++) {
System.out.println("Names----" + stt.get(i).toString());
}
if (j >= 1 && j <= 5) {
Intent i = new Intent(ListViewCheckboxesActivity.this,
PickedItemListView.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
} else {
Toast.makeText(ListViewCheckboxesActivity.this,
"Maximum 5 Selection Allowed", Toast.LENGTH_LONG)
.show();
}
Toast.makeText(ListViewCheckboxesActivity.this, responseText,
Toast.LENGTH_LONG).show();
}
});
}
//Logout ALert Box
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
LayoutInflater inflater = LayoutInflater
.from(ListViewCheckboxesActivity.this);
View dialogview = inflater.inflate(R.layout.logout_popup, null);
final Button ok = (Button) dialogview.findViewById(R.id.ok);
final Button cancel = (Button) dialogview.findViewById(R.id.cancel);
AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(
(ListViewCheckboxesActivity.this));
dialogbuilder.setView(dialogview);
dialogbuilder.setInverseBackgroundForced(true);
alertdialog = dialogbuilder.create();
alertdialog.show();
ok.setOnClickListener(new OnClickListener() {
public void onClick(View paramView) {
alertdialog.dismiss();
final Intent intent = new Intent(
ListViewCheckboxesActivity.this,
LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View paramView) {
alertdialog.cancel();
}
});
}
return super.onKeyDown(keyCode, event);
}
}
checkBox_sound.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
var boolSoundOn = (isChecked) ? true : false;
}
});
It works Perfect...
Related
I want to add / remove the item into wishlist. I am getting one response from Api, so in that i have one tag is_wishlist=true/false, when I am launching an application based on that value I am showing its in wishlist by changing an icon, but now issue is if am changing that wishlist status like from adding to remobing to adding, in Api i am getting response sucessfully, but i am unable to change the icons. This is my code. can any one help me how to remove or add items into wishlist
package com.example.user.smgapp;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.List;
public class Prd_grid_adapter extends BaseAdapter {
List<HashMap<String, String>> Category_listData;
HashMap<String, String> map;
Context context;
Typeface face;
String wishList_url, remove_wishList_url;
Cursor cursor;
NavigationDrawer nav = new NavigationDrawer();
private static LayoutInflater inflater = null;
public Prd_grid_adapter(Activity context, List<HashMap<String, String>> aList) {
// TODO Auto-generated constructor stub
Category_listData = aList;
/*/for(int i=1;i<aList.size();i++)
{
Category_listData.add(aList.get(i));
}*/
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return Category_listData.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 position;
}
public class Holder {
TextView name, price, original_price;
ImageView img, wish_list;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
final View rowView;
this.face = Typeface.createFromAsset(context.getAssets(), "fonts/OpenSans-Regular.ttf");
rowView = inflater.inflate(R.layout.grid_item_view, null);
holder.name = (TextView) rowView.findViewById(R.id.p_name);
holder.img = (ImageView) rowView.findViewById(R.id.p_img);
holder.wish_list = (ImageView) rowView.findViewById(R.id.wish_list);
holder.price = (TextView) rowView.findViewById(R.id.p_price);
holder.original_price = (TextView) rowView.findViewById(R.id.orginal_p);
map = Category_listData.get(position);
holder.name.setTypeface(face);
holder.name.setText(map.get("product_name"));
Log.e("wish list staus..", "wishlist status.." + map.get("is_wishlist"));
if (map.get("is_wishlist").equals("0")) {
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
} else {
holder.wish_list.setImageResource(R.drawable.wishlist);
}
holder.wish_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (SingletonActivity.custidstr.isEmpty()) {
Toast.makeText(context, "Ur not logged in,Please Login", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Alert!");
builder.setMessage("Ur not logged in")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(context, Login.class);
context.startActivity(intent);
}
});
// Create the AlertDialog object and return it
builder.show();
} else {
wishList_url = SingletonActivity.API_URL + "api/add_wishlist.php?customer_id=" + SingletonActivity.custidstr + "&product_id=" + Category_listData.get(position).get("product_id");
remove_wishList_url = SingletonActivity.API_URL + "api/remove_item_wishlist.php?customerid=" + SingletonActivity.custidstr + "&productid=" + Category_listData.get(position).get("product_id");
Log.e("wishlist api..", "wish list api.." + wishList_url);
Log.e("remove wishlist api..", "remove wish list api.." + remove_wishList_url);
v.setActivated(!v.isActivated());
String wish_status = map.get("is_wishlist");
Log.e("wish status..", "wish status.." + wish_status);
int stat = Integer.parseInt(wish_status);
// notifyDataSetChanged();
/*if (wish_status=="Product already exists in wishlist"){
Toast.makeText(context,"removed....",Toast.LENGTH_SHORT).show();
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
}
else
{
nav.addTowishList(wishList_url);
Toast.makeText(context,"addedd..",Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
}*/
if (stat == 0) {
nav.addTowishList(wishList_url);
Toast.makeText(context, "addedd..", Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
// notifyDataSetChanged();
/* ((Activity)context).finish();
Intent i= ((Activity) context).getIntent();
context.startActivity(i);*/
//
} else {
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
Toast.makeText(context, "removed....", Toast.LENGTH_SHORT).show();
/* ((Activity)context).finish();
Intent i= ((Activity) context).getIntent();
context.startActivity(i);*/
// notifyDataSetChanged();
}
/* v.setActivated(!v.isActivated());
if (v.isActivated()){
Toast.makeText(context,"addedd..",Toast.LENGTH_SHORT).show();
holder.wish_list.setImageResource(R.drawable.wishlist);
nav.addTowishList(wishList_url);
}
else {
Toast.makeText(context,"removed....",Toast.LENGTH_SHORT).show();
nav.removeFromwishList(remove_wishList_url);
holder.wish_list.setImageResource(R.drawable.empty_wishlist);
}*/
}
}
});
if (map.get("special_price").equals("0.00")) {
holder.price.setVisibility(View.INVISIBLE);
// holder.o_price.setVisibility(View.INVISIBLE);
holder.original_price.setText("Rs." + map.get("product_price"));
holder.original_price.setTextAppearance(context, R.style.product_price_txt);
} else {
holder.price.setText("Rs." + map.get("special_price"));
holder.original_price.setText("Rs." + map.get("product_price"));
holder.original_price.setPaintFlags(holder.original_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
/* holder.price.setText("Rs." + map.get("special_price"));
holder.original_price.setText("Rs."+map.get("product_price"));
holder.original_price.setPaintFlags(holder.original_price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);*/
Picasso.with(context).load(map.get("product_image")).placeholder(R.drawable.loading)
.fit().into(holder.img);
return rowView;
}
}
Change this line
holder.wish_list.setImageResource(R.drawable.wishlist);
to this
Resources resources = getResources();
holder.wish_list.setImageDrawable(resources.getDrawable(R.drawable.wishlist));
and do the same in else part and check the output..
Note :
getResources().getDrawable is deprecated.
You can try ContextCompat.getDrawable:
holder.wish_list.setImageDrawable(ContextCompat.getDrawable(context,
R.drawable.wishlist));
UpDate :
check this way.
if(state == true){
// here is default icon and set api value and send it
}else{
// here is click wishlist icon and set api value and send it
}
UpDate 2 :
public class FragmentOne_Adapter extends CursorAdapter {
FragmentOne_DbAdapter dbHelper;
public FragmentOne_Adapter(Context context, Cursor c, int flags) {
super(context, c, flags);
// TODO Auto-generated constructor stub
dbHelper = new FragmentOne_DbAdapter(context);
dbHelper.open();
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
// TODO Auto-generated method stub
final ViewHolder holder = (ViewHolder) view.getTag();
final int _id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String title = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String artist = cursor.getString(cursor.getColumnIndexOrThrow("artist"));
String volume = cursor.getString(cursor.getColumnIndexOrThrow("volume"));
final String favorite = cursor.getString(cursor.getColumnIndexOrThrow("favorite"));
String number = cursor.getString(cursor.getColumnIndexOrThrow("number"));
// Populate fields with extracted properties
holder.txtTitle.setText(title);
holder.txtArtist.setText(artist);
holder.txtVolume.setText(volume);
holder.txtNumber.setText(number);
if (favorite.matches("0")) {
holder.buttonHeart.setImageResource(R.drawable.heart);
} else {
if (favorite.matches("1")) {
holder.buttonHeart.setImageResource(R.drawable.heartred);
} else {
holder.buttonHeart.setImageResource(R.drawable.heart);
}
}
holder.buttonHeart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (arg0 != null) {
FragmentOne_DbAdapter database = new FragmentOne_DbAdapter(context);
database.open();
if (favorite.matches("0")) {
database.updateItemFavorite(_id, "1");
holder.buttonHeart.setImageResource(R.drawable.heartred);
} else if (favorite.matches("1")) {
database.updateItemFavorite(_id, "0");
holder.buttonHeart.setImageResource(R.drawable.heart);
}
}
FragmentOne_Adapter.this.changeCursor(dbHelper.fetchAllPlayer1());
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
// View rowView = ((LayoutInflater) context
// .getSystemService("layout_inflater")).inflate(
// R.layout.fragment_fragment_one_slview, parent, false);
View rowView = LayoutInflater.from(context).inflate(R.layout.fragment_fragment_one_slview, parent, false);
ViewHolder holder = new ViewHolder();
holder.txtTitle = (TextView) rowView.findViewById(R.id.title);
holder.txtArtist = (TextView) rowView.findViewById(R.id.artist);
holder.txtVolume = (TextView) rowView.findViewById(R.id.volume);
holder.txtNumber = (TextView) rowView.findViewById(R.id.number);
holder.buttonHeart = (ImageButton) rowView.findViewById(R.id.heart);
rowView.setTag(holder);
return rowView;
}
class ViewHolder {
TextView txtTitle;
TextView txtArtist;
TextView txtVolume;
TextView txtNumber;
ImageButton buttonHeart;
}
}
I created custom ListView with CheckBox next to title. I want to get checked
CheckBox from ListView
I created following function for get message from ListView and send it to another ListView with Intent but I cant get the particular CheckBox position to move.
public class SpamActivity extends AppCompatActivity {
List<Message> sms;
ArrayList<Message> sms1;
ArrayList<String> al;
ListView lv;
CheckBox checkbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messagebox);
lv= (ListView) findViewById(R.id.lvMsg);
checkbox = (CheckBox) findViewById(R.id.checkBox);
sms = new ArrayList<>();
al=new ArrayList<>(0);
populateMessageList();
/* SpamActivity spamactivity = new SpamActivity();
al = spamactivity.al;
//InboxFragment inboxfragment = new InboxFragment();
//al = inboxfragment.list;
for (int i=0;i<sms.size();i++){
System.out.println("AddressSPS" + sms.get(i));
} */
Collections.reverse(sms);
}
public void populateMessageList() {
sms1 = new ArrayList<>();
fetchDatabaseMessage();
lv.setAdapter(new datalist(getApplicationContext(), sms1));
// to handle click event on listView item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
// when user clicks on ListView Item , onItemClick is called
// with position and View of the item which is clicked
// we can use the position parameter to get index of clicked item
TextView textViewSMSSender = (TextView) v.findViewById(R.id.lblNumber);
TextView textViewSMSBody = (TextView) v.findViewById(R.id.lblMsg);
TextView textViewSMSDate = (TextView) v.findViewById(R.id.smsdate);
String smsSender = textViewSMSSender.getText().toString();
String smsBody = textViewSMSBody.getText().toString();
String smsDate = textViewSMSDate.getText().toString();
Intent intentspam = new Intent(getApplicationContext(), DisplaySpamsms.class);
intentspam.putExtra("number",smsSender);
intentspam.putExtra("msg",smsBody);
startActivity(intentspam);
}
});
}
// This method featch the message stored in database
public void fetchDatabaseMessage(){
DB_Message dbmessage = new DB_Message(this);
sms = dbmessage.ViewMessageData();
String addr = sms.get(0).getmAddress();
if (addr.equals(sms.get(0).getmAddress())) {
for (int i = 0; i < sms.size(); i++) {
al.add(sms.get(i).getmAddress());
//al.add(sms.get(i).getmBody());
}
}else {
System.out.println("SMS Not Displayed");
}
}
class datalist extends BaseAdapter {
Context context;
ArrayList<Message> arrayListsms;
public datalist(Context context, ArrayList<Message> arrayListsms) {
// TODO Auto-generated constructor stub
this.context = context;
this.arrayListsms = arrayListsms;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return sms.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return getItem(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
LayoutInflater inflator = getLayoutInflater();
View row;
row = inflator.inflate(R.layout.row, parent, false);
// ImageView img1 = (ImageView) row.findViewById(R.id.imageView1);
final CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkBox);
final TextView txt1 = (TextView) row.findViewById(R.id.lblMsg);
final TextView txt2 = (TextView) row.findViewById(R.id.lblNumber);
final TextView txt3 = (TextView) row.findViewById(R.id.smsdate);
//Long timestamp = Long.parseLong(sms.get(position).getmDate());
Calendar mcalendar = Calendar.getInstance();
//mcalendar.setTimeInMillis(timestamp);
DateFormat mformatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
txt1.setText(sms.get(position).getmBody());
txt2.setText(sms.get(position).getmAddress());
//+"\n"+mformatter.format(mcalendar.getTime())
txt3.setText(mformatter.format(mcalendar.getTime()));
final String msgBody = txt1.getText().toString();
final String msgAddr = txt2.getText().toString();
final String msgDate = txt3.getText().toString();
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Message msg = new Message();
if (isChecked) {
// selectedStrings.add(tv.getText().toString());
Toast.makeText(context, "" + msgBody, Toast.LENGTH_LONG).show();
System.out.println("Body" + msgBody);
System.out.println("Address" + msgAddr);
System.out.println("Date" + msgDate);
al.add(msgBody + msgAddr + msgDate);
// al.add(msgAddr);
// al.add(msgDate);
sms.remove(position);
ContentValues values = new ContentValues();
values.put("address", sms.get(position).getmAddress());
values.put("body", sms.get(position).getmBody());
String date = msg.getmDate();
SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
getContentResolver().insert(Uri.parse("content://sms/inbox"), values);
notifyDataSetChanged();
} else {
// selectedStrings.remove(tv.getText().toString());
}
}
});
return row;
}
}
}
When I used above function for sending message but error is that when I click on any CheckBox to send that message then automatically Different Message is sent to another activity. so, I want to get particular message position to sent it.
You can set "setOnItemClickListener" on list view and get the position.
ListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Here you can get the position
}
});
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class SharedContactListAdapter extends ArrayAdapter<ContactSynResponse> {
private Context context;
private ViewHolder viewHolder;
private SparseBooleanArray mSparseBooleanArray;
private List<ContactSynResponse> mList;
public SharedContactListAdapter(Context context, int resource,
List<ContactSynResponse> objects) {
super(context, resource, objects);
this.context = context;
mSparseBooleanArray = new SparseBooleanArray();
// mList = objects;
}
#Override
public ContactSynResponse getItem(int position) {
return super.getItem(position);
}
public ArrayList<ContactSynResponse> getCheckedItems() {
ArrayList<ContactSynResponse> mTempArry = new ArrayList<ContactSynResponse>();
for (int i = 0; i < mList.size(); i++) {
if (mSparseBooleanArray.get(i)) {
ContactSynResponse data = mList.get(i);
mTempArry.add(data);
}
}
return mTempArry;
}
class ViewHolder {
ImageView profilepic;
ChimmerTextView contactname;
ChimmerTextView contactno;
RelativeLayout completelayout;
CheckBox selectcheckbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.sharedcontactlistdata,
parent, false);
viewHolder = new ViewHolder();
viewHolder.profilepic = (ImageView) convertView
.findViewById(R.id.profilepic_image_view);
viewHolder.contactname = (ChimmerTextView) convertView
.findViewById(R.id.contactnameTV);
viewHolder.contactno = (ChimmerTextView) convertView
.findViewById(R.id.contactnoTV);
viewHolder.completelayout = (RelativeLayout) convertView
.findViewById(R.id.completeRL);
viewHolder.selectcheckbox = (CheckBox) convertView
.findViewById(R.id.contact_checkbox);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
ContactSynResponse data = getItem(position);
viewHolder.contactname.setText(data.getName());
viewHolder.contactno.setText(data.getPhone());
viewHolder.selectcheckbox.setTag(position);
viewHolder.selectcheckbox.setOnCheckedChangeListener(new CheckListener(
data, viewHolder.selectcheckbox));
viewHolder.completelayout.setOnClickListener(new ClickListener(data,
viewHolder.selectcheckbox));
return convertView;
}
class CheckListener implements OnCheckedChangeListener {
private CheckBox checkbox;
public CheckListener(ContactSynResponse data, CheckBox checkbox) {
this.checkbox = checkbox;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
checkbox.setButtonDrawable(R.drawable.notification_selected_checkbox);
} else {
checkbox.setButtonDrawable(R.drawable.notification_checkbox);
}
buttonView.setChecked(isChecked);
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
}
}
class ClickListener implements OnClickListener {
private CheckBox checkbox;
public ClickListener(ContactSynResponse data, CheckBox checkbox) {
this.checkbox = checkbox;
}
#Override
public void onClick(View v) {
if (checkbox.isSelected()) {
checkbox.setChecked(false);
checkbox.setButtonDrawable(R.drawable.notification_checkbox);
mSparseBooleanArray.put((Integer) checkbox.getTag(), false);
} else {
checkbox.setChecked(true);
checkbox.setButtonDrawable(R.drawable.notification_selected_checkbox);
mSparseBooleanArray.put((Integer) checkbox.getTag(), true);
}
}
}
}
**
When i select the items which are at the bottom of the listview,they wont get selected,
rather only first four items in the list is being selected.its because the items are out of view.
what to do to get these items in view ??sometimes the item gets randomly selected.
Please help me.
thank you
Here is my code**
Main activity
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class ExceptionAppActivity extends Activity implements OnClickListener, OnItemSelectedListener {
private final int REQUEST_CODE = 20;
String flagg;
String empNm = Constants.Common.STR_BLNK;
String empCode = Constants.Common.STR_BLNK;
SessionManager session = null;
final Context context = this;
static Typeface custom_font = null;
TextView lblExcId, lblExcEmpNm, lblExcFrmDt, lblExcFrmDtVal, lblExcToDtVal, lblExcTyp, lblExcStat, lblExcEmpCmt;
Button btnExcRej, btnExcApp, btnExcSrch, btnExcExit;
CheckBox cb, chkBox;
ListView excSrchListView;
ArrayList<Excp> Results;
CustomListViewAdapter cla;
ExceptionAppDao eCon = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.exception_app_activity);
/* get Resources from Xml file */
btnExcApp = (Button) findViewById(R.id.btnExcApp);
btnExcRej = (Button) findViewById(R.id.btnExcRej);
btnExcSrch = (Button) findViewById(R.id.btnExcSrch);
btnExcExit = (Button) findViewById(R.id.btnExcExit);
lblExcEmpNm = (TextView) findViewById(R.id.lblExcEmpNm);
lblExcFrmDt = (TextView) findViewById(R.id.lblExcFrmDt);
lblExcFrmDtVal = (TextView) findViewById(R.id.lblExcFrmDtVal);
lblExcToDtVal = (TextView) findViewById(R.id.lblExcToDtVal);
lblExcTyp = (TextView) findViewById(R.id.lblExcTyp);
lblExcStat = (TextView) findViewById(R.id.lblExcStat);
lblExcEmpCmt = (TextView) findViewById(R.id.lblExcEmpCmt);
lblExcId = (TextView) findViewById(R.id.lblExcId);
chkBox = (CheckBox) findViewById(R.id.chkBx);
excSrchListView = (ListView) findViewById(R.id.excSrchListView);
// Session Manager
session = new SessionManager(getApplicationContext());
custom_font = Typeface.createFromAsset(getAssets(), "fonts/DejaVuSans.ttf");
// Connection object for Login
eCon = new ExceptionAppDao(context);
// get User Details from Session
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap = session.getUserDetails();
empNm = hashMap.get(SessionManager.KEY_EMP_NM);
empCode = hashMap.get(SessionManager.KEY_EMP_CODE);
btnExcApp.setTypeface(custom_font);
btnExcRej.setTypeface(custom_font);
btnExcSrch.setTypeface(custom_font);
btnExcExit.setTypeface(custom_font);
new SyncData(empCode).execute();
if (getIntent().getBooleanExtra("EXIT", false)) {
}
// on click any button
addButtonListener();
}
/**
* on click any button
*/
private void addButtonListener() {
btnExcApp.setOnClickListener(this);
btnExcRej.setOnClickListener(this);
btnExcSrch.setOnClickListener(this);
btnExcExit.setOnClickListener(this);
}
public class SyncData extends AsyncTask<String, String, ArrayList<Excp>> {
private final ProgressDialog dialog = new ProgressDialog(context);
List<ExcpMstVo> rtnExcVo = new ArrayList<ExcpMstVo>();
ExcpMstVo rtnExcMstVo = new ExcpMstVo();
ArrayList<Excp> resultLst = new ArrayList<Excp>();
ExceptionService_Service excpServObj = new ExceptionService_Service();
String syncFlg = Constants.Common.STR_BLNK;
private View rootView;
String flag = "";
int x;
boolean success = false;
boolean successSyncFlag = false;
int countApp = 0;
public SyncData(String str) {
syncFlg = str;
}
public SyncData(View rootView) {
// TODO Auto-generated constructor stub
this.rootView = rootView;
}
#Override
protected ArrayList<Excp> doInBackground(String... params) {
ExceptionSearchCriteria vo = new ExceptionSearchCriteria();
ExcpMstVo excpMstVo = new ExcpMstVo();
try {
if (syncFlg.equals(empCode)) {
vo = setAppData(vo);
rtnExcVo = excpServObj.getExceptionPort().searchExceptionApproval(vo);
if (!(rtnExcVo.isEmpty())) {
System.out.println("rtnExcVo" + rtnExcVo.size());
Excp exc = null;
for (ExcpMstVo excMstVo : rtnExcVo) {
exc = new Excp();
exc.setExcId(excMstVo.getExcpId());
exc.setEmpCode(excMstVo.getEmpCode());
exc.setEmpNm(excMstVo.getEmpnm());
exc.setFromDt(excMstVo.getFromDt());
exc.setToDt(excMstVo.getToDt());
exc.setExcType(excMstVo.getExcpType());
exc.setExcStatus(excMstVo.getStatus());
exc.setEmpComments(excMstVo.getEmpComments());
exc.setExcFor(excMstVo.getExcpFor());
exc.setExcReason(excMstVo.getExcpReason());
resultLst.add(exc);
Results = resultLst;
success = true;
}
}
} else if (btnExcApp.equals(rootView.getRootView().findViewById(rootView.getId()))) {
for (x = excSrchListView.getChildCount() - 1; x >= 0; x--) {
cb = (CheckBox) excSrchListView.getChildAt(x).findViewById(R.id.chkBx);
if (cb.isChecked()) {
excpMstVo = setEmpData();
rtnExcMstVo = excpServObj.getExceptionPort().changeExceptionStatus(excpMstVo);
System.out.println("rtnExcMstVo:::::" + rtnExcMstVo.getExcpId());
System.out.println("rtnExcMstVoStatuss:::::" + rtnExcMstVo.getStatus());
countApp++;
success = false;
}
}
/*if (countApp == 0) {
} else*/ if (countApp > 0) {
new SyncData(rootView).execute();
//flagg = false;
}
System.out.println("rtnExcMstVo:::::" + rtnExcMstVo.getExcpId());
System.out.println("rtnExcMstVoStatuss:::::" + rtnExcMstVo.getStatus());
}
// get dump from device
CopyDbFromDevice cd = new CopyDbFromDevice();
cd.copyDbToSdcard(context);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("success::::" + success);
successSyncFlag = success;
System.out.println("successSyncFlag::::::::" + successSyncFlag);
return resultLst;
}
private ExcpMstVo setEmpData() {
ExcpMstVo excpMstVo = new ExcpMstVo();
excpMstVo.setExcpId(Results.get(x).getExcId());
excpMstVo.setFromDt(Results.get(x).getFromDt());
excpMstVo.setStatus(Constants.Status.STAT_APPRV);
excpMstVo.setMngrComments("");
excpMstVo.setApprovedBy(empCode);
excpMstVo.setLoggedInUser(empCode);
return excpMstVo;
}
private ExceptionSearchCriteria setAppData(ExceptionSearchCriteria vo) {
vo.setApprover(empCode);
vo.setStatus(Constants.Status.PENDING_APPROVAL);
return vo;
}
protected void onPostExecute(ArrayList<Excp> searchResults) {
System.out.println("successSyncFlag1::::::::" + successSyncFlag);
if (successSyncFlag == true) {
System.out.println("entering ON POST IF");
cla = new CustomListViewAdapter(ExceptionAppActivity.this, resultLst);
excSrchListView.setAdapter(cla);
}
else {
System.out.println("ENTERING ONPOST ELSE PART ");
System.out.println("successSyncFlag2:;;;;;; " + successSyncFlag);
System.out.println("success2:::::::::::: " + success);
System.out.println("NEW METHOD STARTED:::::;");
if (countApp == 0) {
System.out.println("ENTERING COUNT APP 0 ");
String flag = "checkItemApp";
dialogBox(flag);
} else {
new SyncData(empCode).execute();
String flag = "excApp";
dialogBox(flag);
System.out.println("NEW METHOD STARTED1:::::::::");
}
}
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
#Override
public void onClick(View v) {
int countRej = 0;
int id = v.getId();
Intent intent = null;
if (id == R.id.btnExcApp) {
new SyncData(v).execute();
} else if (id == R.id.btnExcRej) {
int itemPos = 0;
for (int y = excSrchListView.getChildCount() - 1; y >= 0; y--) {
cb = (CheckBox) excSrchListView.getChildAt(y).findViewById(R.id.chkBx);
if (cb.isChecked()) {
itemPos = y;
cla.notifyDataSetChanged();
countRej++;
}
}
// Check if any Exception is selected for Rejection and proceed
// accordingly
if (countRej == 1) {
CustomListViewAdapter cla = (CustomListViewAdapter) excSrchListView.getAdapter();
Object o = cla.getItem(itemPos);
Excp selectedExcp = (Excp) o;
intent = new Intent(getBaseContext(), ExcAppDtlsActivity.class);
intent.putExtra("selectedExcp", selectedExcp);
intent.putExtra("readOnly", false);
startActivityForResult(intent, REQUEST_CODE);
} else if (countRej == 0) {
// show dialogue of Select at least 1
String flag = "checkItemRej";
dialogBox(flag);
} else if (countRej > 1) {
String flag = "checkOnlyOne";
dialogBox(flag);
for (int y = excSrchListView.getChildCount() - 1; y >= 0; y--) {
cb = (CheckBox) excSrchListView.getChildAt(y).findViewById(R.id.chkBx);
if (cb.isChecked()) {
itemPos = y;
cb.setChecked(false);
cla.notifyDataSetChanged();
}
}
}
} else if (id == R.id.btnExcSrch) {
intent = new Intent(this, FurtherSearchActivity.class);
intent.putExtra("readOnly", false);
startActivity(intent);
} else if (id == R.id.btnExcExit) {
finish();
}
}
/**
* create alert dialog
*
* #param flag
*/
private void dialogBox(String flag) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
/*if (flag == "excApp") {
alertDialogBuilder.setTitle("Exception Approved successfully !");
} else*/ if (flag == "checkOnlyOne") {
alertDialogBuilder.setTitle("Please select only one item to reject !");
} else if (flag == "checkItemRej") {
alertDialogBuilder.setTitle("Select Exception to Reject !");
}
/*else if (flag == "checkItemApp") {
alertDialogBuilder.setTitle("Select Exception to Approve !");
} */
else if (flag == "excRej") {
alertDialogBuilder.setTitle("Exception Rejected successfully !");
}
/*else {
alertDialogBuilder.setTitle("Flag - " + flag);
}*/
Dialogbox dbx = new Dialogbox(context);
dbx.createDialogAlert(flag, alertDialogBuilder);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
#Override
protected void
onActivityResult(int requestCode, int resultCode, Intent data) {
// REQUEST_CODE is defined above
/*
* if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) { //
* Extract name value from result extras flagg =
* data.getExtras().getString("flagg"); if ((flagg.equals("Approve")) ||
* (flagg.equals("Reject"))) { for (int x = 0; x <
* excSrchListView.getChildCount(); x++) { cb = (CheckBox)
* excSrchListView.getChildAt(x).findViewById( R.id.chkBx); if
* (cb.isChecked()) { // If Approval is successful remove from list
* Results.remove(x); cb.setChecked(false); cla.notifyDataSetChanged();
* if (flagg.equals("Approve")) { dialogBox("excApp"); } else {
* dialogBox("excRej"); } } }
*
* } }
*/
}
}
CUSTOM LIST ADAPTER
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TableLayout;
import android.widget.TextView;
import com.eanda.smarttime_mobi.R;
import com.eanda.smarttime_mobi.model.Excp;
public class CustomListViewAdapter extends BaseAdapter {
private static ArrayList<Excp> searchArrayList;
HashMap<Integer, Boolean> checked;
private LayoutInflater mInflater;
Typeface custom_font = null;
public CustomListViewAdapter(Context context, ArrayList<Excp> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
checked = new HashMap<Integer, Boolean>(getCount());
custom_font = Typeface.createFromAsset(context.getAssets(), "fonts/DejaVuSans.ttf");
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
// created custom view
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.myTable = (TableLayout) convertView.findViewById(R.id.myTable);
holder.txtExcId = (TextView) convertView.findViewById(R.id.lblExcId);
holder.txtEmpNm = (TextView) convertView.findViewById(R.id.lblExcEmpNm);
holder.txtFrmDt = (TextView) convertView.findViewById(R.id.lblExcFrmDtVal);
holder.txtToDt = (TextView) convertView.findViewById(R.id.lblExcToDtVal);
holder.txtExcTyp = (TextView) convertView.findViewById(R.id.lblExcTyp);
holder.txtExcStat = (TextView) convertView.findViewById(R.id.lblExcStat);
holder.txtEmpCmt = (TextView) convertView.findViewById(R.id.lblExcEmpCmt);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);
convertView.setTag(holder);
convertView.setTag(R.id.chkBx, holder.checkBox);
} else {
holder = (ViewHolder) convertView.getTag();
}
System.out.println("exception_name" + searchArrayList.get(position).getEmpNm());
holder.txtExcId.setText(Integer.toString(searchArrayList.get(position).getExcId()));
holder.txtEmpNm.setText(searchArrayList.get(position).getEmpNm());
holder.txtFrmDt.setText(searchArrayList.get(position).getFromDt());
holder.txtToDt.setText(searchArrayList.get(position).getToDt());
holder.txtExcTyp.setText(searchArrayList.get(position).getExcType());
holder.txtExcStat.setText(searchArrayList.get(position).getExcStatus());
holder.txtEmpCmt.setText(searchArrayList.get(position).getEmpComments());
holder.checkBox.setTag(position);
holder.checkBox.setChecked(searchArrayList.get(position).isChecked());
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
System.out.println("selected");
int checkBoxId = (Integer) buttonView.getTag();
holder.checkBox.setChecked(buttonView.isChecked() ? true : false);
searchArrayList.get(checkBoxId).setChecked(buttonView.isChecked() ? true : false);
System.out.println("checkBoxId " + checkBoxId);
}
});
holder.checkBox.setTag(position);
holder.txtExcId.setTypeface(custom_font);
holder.txtEmpNm.setTypeface(custom_font);
holder.txtFrmDt.setTypeface(custom_font);
holder.txtToDt.setTypeface(custom_font);
holder.txtExcTyp.setTypeface(custom_font);
holder.txtExcStat.setTypeface(custom_font);
holder.txtEmpCmt.setTypeface(custom_font);
return convertView;
}
static class ViewHolder {
TableLayout myTable;
TextView txtExcId;
TextView txtEmpNm;
TextView txtFrmDt;
TextView txtToDt;
TextView txtExcTyp;
TextView txtExcStat;
TextView txtEmpCmt;
CheckBox checkBox;
}
}
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);
You already have check box reference stored in the holder, I wonder why you are initializing it again.
holder.checkBox.setChecked(buttonView.isChecked() ? true : false);
Checked state will be changed when the user clicks the checkbox, so no need to change the checked state again.
Try the following code
----
----
holder.checkBox.setTag(position);
holder.checkBox.setChecked(searchArrayList.get(position).isChecked());
holder.checkBox..setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
System.out.println("selected");
int checkBoxId = (Integer) buttonView.getTag();
searchArrayList.get(checkBoxId).setChecked(buttonView.isChecked() ? true : false);
System.out.println("checkBoxId " + checkBoxId);
}
});
holder.checkBox.setTag(position);
-----
----
I want to create a custom listview in which every single row has a textview and an imageview(which i'll use to check/uncheck the list items) as shown in the following figure:
I want to delete multiple items from the list. How to achieve this ?? Can you please provide any tutorial or reference or link to learn this ??
This is how i created my custom listview with ease:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
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.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class DeleteData extends Activity {
Cursor cursor;
ListView lv_delete_data;
static ArrayList<Integer> listOfItemsToDelete;
SQLiteDatabase database;
private Category[] categories;
ArrayList<Category> categoryList;
private ArrayAdapter<Category> listAdapter;
ImageView iv_delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_data);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
manage_reload_list();
listOfItemsToDelete = new ArrayList<Integer>();
iv_delete = (ImageView) findViewById(R.id.imageViewDeleteDataDelete);
iv_delete.setClickable(true);
iv_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (listOfItemsToDelete.isEmpty()) {
Toast.makeText(getBaseContext(), "No items selected.",
Toast.LENGTH_SHORT).show();
}
else {
showDialog(
"Warning",
"Are you sure you want to delete these categories ? This will erase all records attached with it.");
}
}
});
lv_delete_data = (ListView) findViewById(R.id.listViewDeleteData);
lv_delete_data.setAdapter(listAdapter);
lv_delete_data.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) arg1
.findViewById(R.id.imageViewSingleRowDeleteData);
Category category = (Category) imageView.getTag();
if (category.getChecked() == false) {
imageView.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
category.setChecked(true);
} else {
imageView.setImageResource(R.drawable.set_basecircle);
listOfItemsToDelete.remove((Integer) category.getId());
category.setChecked(false);
}
}
});
}
private void showDialog(final String title, String message) {
AlertDialog.Builder adb = new Builder(DeleteData.this);
adb.setTitle(title);
adb.setMessage(message);
adb.setIcon(R.drawable.ic_launcher);
String btn = "Ok";
if (title.equals("Warning")) {
btn = "Yes";
adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
adb.setPositiveButton(btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
if (title.equals("Warning")) {
for (int i : listOfItemsToDelete) {
// -------first delete from category table-----
database.delete("category_fields", "cat_id=?",
new String[] { i + "" });
// --------now fetch rec_id where cat_id =
// i-----------------
cursor = database.query("records_data",
new String[] { "rec_id" }, "cat_id=?",
new String[] { i + "" }, null, null, null);
if (cursor.getCount() == 0)
cursor.close();
else {
ArrayList<Integer> al_tmp_rec_id = new ArrayList<Integer>();
while (cursor.moveToNext())
al_tmp_rec_id.add(cursor.getInt(0));
cursor.close();
for (int i1 : al_tmp_rec_id) {
database.delete("records_fields_data",
"rec_id=?", new String[] { i1 + "" });
database.delete("record_tag_relation",
"rec_id=?", new String[] { i1 + "" });
}
// ---------delete from records_data-------
database.delete("records_data", "cat_id=?",
new String[] { i + "" });
cursor.close();
}
}
showDialog("Success",
"Categories, with their records, deleted successfully.");
} else {
database.close();
listOfItemsToDelete.clear();
manage_reload_list();
lv_delete_data.setAdapter(listAdapter);
}
}
});
AlertDialog ad = adb.create();
ad.show();
}
protected void manage_reload_list() {
loadDatabase();
categoryList = new ArrayList<Category>();
// ------first fetch all categories name list-------
cursor = database.query("category", new String[] { "cat_id",
"cat_description" }, null, null, null, null, null);
if (cursor.getCount() == 0) {
Toast.makeText(getBaseContext(), "No categories found.",
Toast.LENGTH_SHORT).show();
cursor.close();
} else {
while (cursor.moveToNext()) {
categories = new Category[] { new Category(cursor.getInt(0),
cursor.getString(1)) };
categoryList.addAll(Arrays.asList(categories));
}
cursor.close();
}
listAdapter = new CategoryArrayAdapter(this, categoryList);
}
static class Category {
String cat_name = "";
int cat_id = 0;
Boolean checked = false;
Category(int cat_id, String name) {
this.cat_name = name;
this.cat_id = cat_id;
}
public int getId() {
return cat_id;
}
public String getCatName() {
return cat_name;
}
public Boolean getChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
public boolean isChecked() {
return checked;
}
public void toggleChecked() {
checked = !checked;
}
}
static class CategoryViewHolder {
ImageView imageViewCheck;
TextView textViewCategoryName;
public CategoryViewHolder(ImageView iv_check, TextView tv_category_name) {
imageViewCheck = iv_check;
textViewCategoryName = tv_category_name;
}
public ImageView getImageViewCheck() {
return imageViewCheck;
}
public TextView getTextViewCategoryName() {
return textViewCategoryName;
}
}
static class CategoryArrayAdapter extends ArrayAdapter<Category> {
LayoutInflater inflater;
public CategoryArrayAdapter(Context context, List<Category> categoryList) {
super(context, R.layout.single_row_delete_data,
R.id.textViewSingleRowDeleteData, categoryList);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Category category = (Category) this.getItem(position);
final ImageView imageViewCheck;
final TextView textViewCN;
if (convertView == null) {
convertView = inflater.inflate(R.layout.single_row_delete_data,
null);
imageViewCheck = (ImageView) convertView
.findViewById(R.id.imageViewSingleRowDeleteData);
textViewCN = (TextView) convertView
.findViewById(R.id.textViewSingleRowDeleteData);
convertView.setTag(new CategoryViewHolder(imageViewCheck,
textViewCN));
}
else {
CategoryViewHolder viewHolder = (CategoryViewHolder) convertView
.getTag();
imageViewCheck = viewHolder.getImageViewCheck();
textViewCN = viewHolder.getTextViewCategoryName();
}
imageViewCheck.setFocusable(false);
imageViewCheck.setFocusableInTouchMode(false);
imageViewCheck.setClickable(true);
imageViewCheck.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageView iv = (ImageView) v;
Category category = (Category) iv.getTag();
if (category.getChecked() == false) {
imageViewCheck.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
category.setChecked(true);
} else {
imageViewCheck
.setImageResource(R.drawable.set_basecircle);
listOfItemsToDelete.remove((Integer) category.getId());
category.setChecked(false);
}
}
});
imageViewCheck.setTag(category);
if (category.getChecked() == true)
imageViewCheck.setImageResource(R.drawable.set_check);
else
imageViewCheck.setImageResource(R.drawable.set_basecircle);
textViewCN.setText(category.getCatName());
return convertView;
}
}
private void loadDatabase() {
database = openOrCreateDatabase("WalletAppDatabase.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Anyone who have doubts in this can ask me...
Fisrt of all make a custom adapter and row layout for your listview. Follow this link (click) for that.Then add check-box to each row.You can customize check-box to achieve like the image you have posted.To do that, check this link (click)
After creating your custom listview, you have to get the checked listview row id on checkbox click in custom adapter(inside getview method).When the user click a checkbox you have to get the clicked row id and store into an array list.Lets say, your selected id-array list is "ArrayId" and your listview items array list is "Yourarray". here is the code,
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked)
{
ArrayId.add(Yourlist.get(position));//add item position to arraylist if checked
}
else
{
ArrayId.remove(Yourlist.get(position));//remove item position from arraylist if unchecked
}
}
}
Then you loop through each id stored in arraylist and delete the entry.Check the code below,
for(int i=0;i<ArrayId.size();i++)
{
Yourlist.remove(ArrayId[i]);
}
Now the items from your listview items array-"Yourlist" will be removed.Then invalidate the listview with updated "Yourlist" array.
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
}
});