Refresh ListView pressing option DialogFragment - android

I have a listview that clicking on an element shows a DialogFragmen with several options, options that take the user will be shown in the item of listview TextView and I get the following error in execution:
Activity app.gepv.Inventario has leaked IntentReceiver com.immersion.android.haptics.HapticFeedbackManager$HapticFeedbackBroadcastReceiver#426e94b8 that was originally registered here. Are you missing a call to unregisterReceiver()?
Enter the code that I think is important, if you need anything else edit the question :)
This is mi DialogFragment:
final String[] items= equiDisp.toArray(new String[equiDisp.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Asigne equipo/equipos:")
.setOnKeyListener(new Dialog.OnKeyListener(){
public boolean onKey(DialogInterface arg0, int keyCode,KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK)
{
finish();
//dialog.dismiss();
actualizarDisplay();
}
return true;
}
})
.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int item, boolean isChecked) {
Log.i("Dialogos", "Opción elegida: " + items[item]);
if(isChecked)
{
marcado.add(items[item]);
Log.i("Dialogos", "Marcado: " + items[item]);
obras.get(pulsado).equiA.add(Integer.parseInt(items[item]));
for( int k=0; k< obras.get(pulsado).equiA.size(); k++)
{
Log.i("Dialogos", "Equipos: " + obras.get(pulsado).equiA.get(k) );
}
}
}
});
So far everything is running well because I check with Log.i
This is the function ActualizarDisplay():
public void actualizarDisplay()
{
adapter = new ObrasAdapter(this, obras);
lvObras = (ListView) findViewById(R.id.lvItems);
lvObras.setAdapter(adapter);
lvObras.setOnItemClickListener(this);
}
And this is my custom dataApdapter for the listview:
public class ObrasAdapter extends ArrayAdapter<Obra> {
private Context context;
private ArrayList<Obra> datos;
public ObrasAdapter(Context context, ArrayList<Obra> datos) {
super(context, R.layout.listview_item, datos);
this.context = context;
this.datos = datos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View item = convertView;
ObrasHolder holder;
if (item == null) {
item = LayoutInflater.from(context).inflate(R.layout.listview_item,
null);
holder = new ObrasHolder();
holder.foto = (ImageView) item.findViewById(R.id.imgAnimal);
holder.num = (TextView) item.findViewById(R.id.numC);
holder.iden = (TextView) item.findViewById(R.id.idenC);
holder.ubi = (TextView) item.findViewById(R.id.ubiC);
holder.hombres = (TextView) item.findViewById(R.id.homC);
holder.material = (TextView) item.findViewById(R.id.matC);
holder.eq1 = (TextView) item.findViewById(R.id.eq1);
holder.eq2 = (TextView) item.findViewById(R.id.eq2);
holder.eq3 = (TextView) item.findViewById(R.id.eq3);
holder.eq4 = (TextView) item.findViewById(R.id.eq4);
holder.fondo = (RelativeLayout) item.findViewById(R.id.fondobra);
item.setTag(holder);
}
holder = (ObrasHolder) item.getTag();
holder.foto.setImageResource(datos.get(position).getDrawableImageID());
if(datos.get(position).getPrioridad()==1)
{
holder.num.setTextColor(Color.RED);
holder.iden.setTextColor(Color.RED);
holder.ubi.setTextColor(Color.RED);
holder.hombres.setTextColor(Color.RED);
holder.material.setTextColor(Color.RED);
holder.eq1.setTextColor(Color.RED);
holder.eq2.setTextColor(Color.RED);
holder.eq3.setTextColor(Color.RED);
holder.eq4.setTextColor(Color.RED);
}
if(datos.get(position).getPrioridad()==2)
{
holder.num.setTextColor(Color.parseColor("#FF8000"));
holder.iden.setTextColor(Color.parseColor("#FF8000"));
holder.ubi.setTextColor(Color.parseColor("#FF8000"));
holder.hombres.setTextColor(Color.parseColor("#FF8000"));
holder.material.setTextColor(Color.parseColor("#FF8000"));
holder.eq1.setTextColor(Color.parseColor("#FF8000"));
holder.eq2.setTextColor(Color.parseColor("#FF8000"));
holder.eq3.setTextColor(Color.parseColor("#FF8000"));
holder.eq4.setTextColor(Color.parseColor("#FF8000"));
}
if(datos.get(position).getPrioridad()==3)
{
holder.num.setTextColor(Color.GREEN);
holder.iden.setTextColor(Color.GREEN);
holder.ubi.setTextColor(Color.GREEN);
holder.hombres.setTextColor(Color.GREEN);
holder.material.setTextColor(Color.GREEN);
holder.eq1.setTextColor(Color.GREEN);
holder.eq2.setTextColor(Color.GREEN);
holder.eq3.setTextColor(Color.GREEN);
holder.eq4.setTextColor(Color.GREEN);
}
holder.num.setText(datos.get(position).getNum());
holder.iden.setText(datos.get(position).getIden());
holder.ubi.setText(datos.get(position).getUb());
holder.hombres.setText(datos.get(position).getHom());
holder.material.setText(datos.get(position).getMat());
if(datos.get(position).getEstado()==1)
{
holder.fondo.setBackgroundColor(Color.GREEN);
holder.num.setTextColor(Color.WHITE);
holder.iden.setTextColor(Color.WHITE);
holder.ubi.setTextColor(Color.WHITE);
holder.hombres.setTextColor(Color.WHITE);
holder.material.setTextColor(Color.WHITE);
holder.eq1.setTextColor(Color.WHITE);
holder.eq1.setTextColor(Color.WHITE);
holder.eq1.setTextColor(Color.WHITE);
holder.eq1.setTextColor(Color.WHITE);
}
if(! datos.get(position).equiA.isEmpty())
{
for(int i=0; i<datos.get(position).equiA.size();i++)
{
if(i == 0)
{
holder.eq1.setText(String.valueOf(datos.get(position).equiA.get(i)));
}
if(i == 1)
holder.eq2.setText(String.valueOf(datos.get(position).equiA.get(i)));
if(i == 2)
holder.eq3.setText(String.valueOf(datos.get(position).equiA.get(i)));
if(i == 3)
holder.eq4.setText(String.valueOf(datos.get(position).equiA.get(i)));
}
}
else
{
holder.eq1.setVisibility(View.INVISIBLE);
holder.eq2.setVisibility(View.INVISIBLE);
holder.eq3.setVisibility(View.INVISIBLE);
holder.eq4.setVisibility(View.INVISIBLE);
}
return item;
}
}
Can anyone help me?
I think i must to do something as:
#Override
protected void onStop()
{
unregisterReceiver(sendBroadcastReceiver);
unregisterReceiver(deliveryBroadcastReceiver);
super.onStop();
}

Related

Deleting item from Listview in onActivityResult

I'm hoping that someone here could help me. I'm trying to delete an item from my Listview by clicking a button from another activity. I'm sending a an intent and resultcode in the onActivityResult to the activity that contains the listview but nothing is happening. Any help would be greatly appreciated. Thanks
Delete Button Activity
private void deleteClicked() {
Intent result = new Intent();
result.putExtra("myReminder", item);
getActivity() .setResult(12, result);
getActivity().finish();
}
ListView Activity
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
Log.e(TAG, "REMOVE CALLEDcode");
if (requestCode == 05) {
if (resultCode == 12) {
Chops item = (Chops) data.getSerializableExtra("myReminder");
removeChop(item);
refreshFragment();
}
}
}
private void removeChop(Chops item) {
// TODO Auto-generated method stub
Log.d(TAG, "REMOVE CALLED");
for (Iterator iterator = SaveTheChops.listofchops.iterator(); iterator.hasNext(); ) {
Chops deleteChop = (Chops) iterator.next();
if (match(item, deleteChop)) {
iterator.remove();
//SaveTheChops.addChop(getActivity());
return;
}
}
}
private boolean match(Chops item, Chops deleteChop) {
if (item.getmAlbum().equals(deleteChop.getmAlbum()) &
item.getmArtist().equals(deleteChop.getmArtist()) &
item.getmSong().equals(deleteChop.getmSong()) &
item.getmAudio().equals(deleteChop.getmAudio()) &
item.getmPic().equals(deleteChop.getmPic()) &
item.getmSection().equals(deleteChop.getmSection()))
{ Log.e(TAG, "MATCH");
return true;
}
Log.e(TAG, " NO MATCH");
return false;
}
private void refreshFragment() {
Log.e(TAG, "REFRESHED");
Fragment frg = null;
frg = getFragmentManager().findFragmentByTag("ListFragmenttag");
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();
}
}
If it helps here is my ListAdapter
public static class ListViewDemoAdapter extends ArrayAdapter<Chops> implements MediaPlayer.OnCompletionListener {
final String TAG = "MyChopActivty";
private boolean isPlaying;
private boolean isRecording;
private List<Chops> mItems;
MediaPlayer mPlayer;
public Chops item;
File audiofile = null;
private int length;
Intent intent, fileIntent;
String mAudio;
public ListViewDemoAdapter(Context context, List<Chops> items) {
super(context, R.layout.each_item, items);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
final LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.each_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.cover_photo);
viewHolder.tvAlbum = (TextView) convertView.findViewById(R.id.tvAlbum);
viewHolder.tvPlay = (Button) convertView.findViewById(R.id.listPly);
viewHolder.tvSong = (TextView) convertView.findViewById(R.id.tvSong);
convertView.setTag(viewHolder);
final Button PIL = (Button) convertView.findViewById(R.id.listPly);
final Button PAUSIL = (Button) convertView.findViewById(R.id.listPause);
PAUSIL.setEnabled(false);
PAUSIL.setVisibility(View.INVISIBLE);
PIL.setTag(position);
PIL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
Chops item = getItem(position);
Toast.makeText(getContext(), "PLAY FROM LIST?", Toast.LENGTH_SHORT).show();
if (item.getmAudio() != null) {
mAudio = item.getmAudio();
Log.d(TAG, " from LISTPLAY " + mAudio);
try {
playAudio(mAudio);
if (isPlaying) {
PAUSIL.setEnabled(true);
PAUSIL.setVisibility(View.VISIBLE);
PIL.setEnabled(false);
PIL.setVisibility(View.INVISIBLE);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
PAUSIL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "PAUSING", Toast.LENGTH_SHORT).show();
stopPlaying();
isPlaying = false;
PAUSIL.setEnabled(false);
PAUSIL.setVisibility(View.INVISIBLE);
PIL.setEnabled(true);
PIL.setVisibility(View.VISIBLE);
}
});
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Chops item = getItem(position);
viewHolder.ivIcon.setImageBitmap(StringToBitMap(item.getmPic()));
viewHolder.tvAlbum.setText(item.getmAlbum());
viewHolder.tvSong.setText(item.getmSong());
return convertView;
}
Instead, Add a method to remove an item from your dataset inside your Adapter class. Something along the lines of:
public void remove(int position){
mItems.remove(position);
notifyDataSetChanged();
}
Then call yourAdapter.remove(positionToRemove); from the onClick of the Activity with the button.

Android list view change text when row is deleted

I have a ListView, which has an hidden button which become visible on user long click on row.
If someone clicks this button, the row is deleted.
My rows are composed by transactions, and in the same Activity i got a TextView displaying the amount.
When I add a transaction, my text is changed and the budget updated. My problem is updating it when an user clicks the button and deletes a row.
here is my adapter class
public class HomePageListAdapter extends ArrayAdapter<TRANSAZIONE> {
ArrayList<TRANSAZIONE> transazioni;
public HomePageListAdapter(Context context, int textViewResourceId,
ArrayList<TRANSAZIONE> objects) {
super(context, textViewResourceId, objects);
transazioni = objects;
}
TRANSAZIONE transazione;
NumberFormat formatter = new DecimalFormat("#0.00");
#Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.adapter_home_page_list, null);
TextView tvDesc = (TextView) view.findViewById(R.id.tvDescription);
TextView tvAmou = (TextView) view.findViewById(R.id.tvAmount);
final Button btnElimina = (Button) view.findViewById(R.id.btnElimina);
transazione = transazioni.get(position);
String dText = transazione.getDescription();
String aText = "";
if(transazione.getAmount() != null) {
aText = formatter.format(transazione.getAmount()) + " €";
if (transazione.getAmount() > 0) {
tvAmou.setTextColor(Color.GREEN);
} else {
tvAmou.setTextColor(Color.RED);
}
}
tvDesc.setText(dText);
tvAmou.setText(aText);
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
btnElimina.setVisibility(View.VISIBLE);
return false;
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btnElimina.getVisibility() == View.VISIBLE) {
btnElimina.setVisibility(View.GONE);
}
}
});
btnElimina.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new TRANSAZIONE().Delete(TRANSAZIONE.class, getContext(), "where id = '" + transazioni.get(position).getId() + "'");
Toast.makeText(getContext(), "Transazione eliminata.", Toast.LENGTH_SHORT).show();
transazioni.remove(position);
notifyDataSetChanged();
} catch (Exception ex) {
Toast.makeText(getContext(), "Errore non gestito.", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
It works properly, and I have no problems updating my layout.
** And this is the method which updates my TextView's text and calls the Adapter. It's in the Activity**
public void LoadTotal() throws Exception {
#SuppressWarnings("unchecked")
ArrayList<TRANSAZIONE> transazioni = (ArrayList<TRANSAZIONE>) new TRANSAZIONE().SelectAll(TRANSAZIONE.class, getContext(), "");
Double totale = Settings.getLimitAmount();
//prendo solo quelle del mese corrente
if (transazioni.size() > 0) {
int numeroAggiornamento = Settings.getResettingDay();
Calendar today = Calendar.getInstance();
Calendar transactionDate = Calendar.getInstance();
Calendar lastChangeDate = Calendar.getInstance();
lastChangeDate.set(Calendar.DAY_OF_MONTH, numeroAggiornamento);
if (today.get(Calendar.DAY_OF_MONTH) < numeroAggiornamento) {
lastChangeDate.add(Calendar.MONTH, -1);
}
for (TRANSAZIONE t : transazioni) {
transactionDate.setTime(t.getDate());
if (transactionDate.compareTo(lastChangeDate) == -1) {
transazioni.remove(t);
} else {
totale += t.getAmount();
}
}
}
if (transazioni.size() == 0) {
transazioni.add(new TRANSAZIONE("Nessuna transazione per il mese in corso.", null, null));
}
HomePageListAdapter adapter = new HomePageListAdapter(getContext(), R.layout.adapter_home_page_list, transazioni);
lvTransactions.setAdapter(adapter);
tvBudget.setText(formatter.format(totale));
}
My problem is the following:
When I delete a row, it disappears from the list, but I can't intercept this in my Activity.
I need someway to call the method LoadTotal() when my row is deleted.
Any help will be appreciated.
Thanks all and sorry for my not perfect English.
The cleanest way of doing it is by using a DataSetObserver.
Inside your activity you have this object:
private DataSetObserver adapterObserver = new DataSetObserver() {
#Override
public void onChanged(){
// here you call your method
LoadTotal();
}
}
and then you register/unreguster this observer during onResume/onPause
#Override
public void onResume(){
super.onResume();
LoadTotal(); // update with latest values
adapter.registerDataSetObserver(adapterObserver);
}
#Override
public void onPause(){
super.onPause();
adapter.unregisterDataSetObserver(adapterObserver);
}
edit: some debug info for the op.
here is the code for notifyDataSetChanged() from BaseAdapter
public void notifyDataSetChanged() {
mDataSetObservable.notifyChanged();
}
and then inside DataSetObservable is simply looping through the list of observers
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onChanged();
}
That means there's very little to actually go wrong there. But it's important to understand what is happening. So my suggestion is to put a breakpoint on all the method calls: onPause, onResume, onChanged and the line you call notifyDataSetChanged. And run it with the debugger, so you can see what is being called when and find out why it's not working.
In your adapter class
public class HomePageListAdapter extends ArrayAdapter<TRANSAZIONE> {
Context context;
ArrayList<TRANSAZIONE> transazioni;
public HomePageListAdapter(Context context, int textViewResourceId,
ArrayList<TRANSAZIONE> objects) {
super(context, textViewResourceId, objects);
transazioni = objects;
this.context=context;
}
TRANSAZIONE transazione;
NumberFormat formatter = new DecimalFormat("#0.00");
#Override
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.adapter_home_page_list, null);
TextView tvDesc = (TextView) view.findViewById(R.id.tvDescription);
TextView tvAmou = (TextView) view.findViewById(R.id.tvAmount);
final Button btnElimina = (Button) view.findViewById(R.id.btnElimina);
transazione = transazioni.get(position);
String dText = transazione.getDescription();
String aText = "";
if(transazione.getAmount() != null) {
aText = formatter.format(transazione.getAmount()) + " €";
if (transazione.getAmount() > 0) {
tvAmou.setTextColor(Color.GREEN);
} else {
tvAmou.setTextColor(Color.RED);
}
}
tvDesc.setText(dText);
tvAmou.setText(aText);
view.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
btnElimina.setVisibility(View.VISIBLE);
return false;
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btnElimina.getVisibility() == View.VISIBLE) {
btnElimina.setVisibility(View.GONE);
}
}
});
btnElimina.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new TRANSAZIONE().Delete(TRANSAZIONE.class, getContext(), "where id = '" + transazioni.get(position).getId() + "'");
Toast.makeText(getContext(), "Transazione eliminata.", Toast.LENGTH_SHORT).show();
transazioni.remove(position);
notifyDataSetChanged();
} catch (Exception ex) {
Toast.makeText(getContext(), "Errore non gestito.", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
You can call the method of your activity like
((YourActivityName)context).LoadTotal();

ListView CheckBox getting multi selected on just clicking only one time

I'm trying to use CheckBox in my ListView with an ArrayAdapter. When I select any CheckBox onlytime in the list, multiple entries are selected automatically in a random order. Can anyone please tell how I can avoid this.
Here's my code for your reference:
public class SearchListAdapterQ2 extends BaseAdapter {
int layoutId;
ArrayList<SearchListView> searchresultList = new ArrayList<SearchListView>();
public static int companyCpsId;
public static String companyCpsType = "", search_companyName = "",
search_countryName = "", handShakeStatus = "";
public static String handShakeCPSName = "";
public static boolean searchListAdapter_Q2 = false;
SharedPreferences sharedpreferences;
boolean markfavStatus = false;
ListView searchResults_listView;
Context context;
public SearchListAdapterQ2(Context context, int layoutId,
ArrayList<SearchListView> searchresultList,
ListView searchResults_listView) {
// TODO Auto-generated constructor stub
this.layoutId = layoutId;
this.searchresultList = searchresultList;
Log.i("inside searchListAdapter", "inside searchListAdapter");
this.context = context;
sharedpreferences = context.getSharedPreferences("MyPrefs",
Context.MODE_PRIVATE);
this.searchResults_listView = searchResults_listView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
Log.i("searchresultList",
"searchresultList: " + searchresultList.size());
return searchresultList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return searchresultList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder1 holder1;
// LayoutInflater inflater = (LayoutInflater)
// context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
char color;
String text = "";
String address = "";
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.qq_searchlist_repeat_items,
parent, false);
holder1 = new ViewHolder1();
holder1.companyName_textView = (TextView) convertView
.findViewById(R.id.companyName_textView);
holder1.companyLogo_textView = (TextView) convertView
.findViewById(R.id.companyLogo_textView);
holder1.companyAddress_textView = (TextView) convertView
.findViewById(R.id.companyAddress_textView);
holder1.handShakeIcon_imageView = (ImageView) convertView
.findViewById(R.id.handShakeIcon_imageView);
holder1.favouritesIcon_imageView = (ImageView) convertView
.findViewById(R.id.favouritesIcon_imageView);
holder1.referIcon_imageView = (ImageView) convertView
.findViewById(R.id.referIcon_imageView);
holder1.sendEnquiry_imageView = (ImageView) convertView
.findViewById(R.id.sendEnquiry_imageView);
holder1.icons_searchResultsPage_relLayout = (RelativeLayout) convertView
.findViewById(R.id.icons_searchResultsPage_relLayout);
holder1.chckbx1 = (CheckBox) convertView.findViewById(R.id.chckbx1);
if (SearchListActivity_Q2.broadcastMode) {
Log.i("icons_searchResultsPage_relLayout is visible",
"icons_searchResultsPage_relLayout is visible");
holder1.icons_searchResultsPage_relLayout
.setVisibility(View.GONE);
holder1.chckbx1.setVisibility(View.VISIBLE);
} else {
holder1.icons_searchResultsPage_relLayout
.setVisibility(View.VISIBLE);
holder1.chckbx1.setVisibility(View.GONE);
}
convertView.setTag(holder1);
} else {
holder1 = (ViewHolder1) convertView.getTag();
}
holder1.id = position;
search_companyName = searchresultList.get(position).getCpsName();
search_countryName = searchresultList.get(position).getCountryName();
try {
String ssearch_companyName = URLDecoder.decode(search_companyName,
"UTF-8");
holder1.companyName_textView.setText(ssearch_companyName);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (searchresultList.get(position).getCpsName().contains(" ")) {
String[] splitText = searchresultList.get(position).getCpsName()
.split("\\s+");
char a = splitText[0].charAt(0);
char b = splitText[1].charAt(0);
text = String.valueOf(a) + String.valueOf(b);
color = b;
} else {
text = searchresultList.get(position).getCpsName().substring(0, 1);
color = searchresultList.get(position).getCpsName().charAt(1);
}
holder1.companyLogo_textView.setText(text.toUpperCase());
if (searchresultList.get(position).getCpsAddress().isEmpty()) {
address = searchresultList.get(position).getCountryName();
} else {
if (searchresultList.get(position).getCpsAddress().length() > 1) {
address = searchresultList.get(position).getCpsAddress() + ", "
+ searchresultList.get(position).getCountryName();
} else {
address = searchresultList.get(position).getCountryName();
}
}
holder1.companyAddress_textView.setText(address);
holder1.companyName_textView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
searchListAdapter_Q2 = true;
companyCpsId = searchresultList.get(position)
.getCpsId();
Log.i("$$$ companyCpsId", "companyCpsId" + companyCpsId);
companyCpsType = searchresultList.get(position)
.getCpsType();
Intent intent = new Intent(context,
CompanyProfile_Activity.class);
context.startActivity(intent);
}
});
holder1.referIcon_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
holder1.sendEnquiry_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Q2_SendEnquiryList> sendEnquiry = new ArrayList<Q2_SendEnquiryList>();
sendEnquiry.add(new Q2_SendEnquiryList(searchresultList
.get(position).getCpsId(), searchresultList
.get(position).getCpsName()));
sendEnquiry.add(new Q2_SendEnquiryList(1, "abcdefgh"));
sendEnquiry.add(new Q2_SendEnquiryList(2, "abcdefg"));
sendEnquiry.add(new Q2_SendEnquiryList(3, "abcdef"));
sendEnquiry.add(new Q2_SendEnquiryList(4, "abcde"));
sendEnquiry.add(new Q2_SendEnquiryList(5, "abcd"));
sendEnquiry.add(new Q2_SendEnquiryList(6, "abc"));
sendEnquiry.add(new Q2_SendEnquiryList(7, "ab"));
Intent intent = new Intent(context,
Q2_SendEnquiryActivity.class);
intent.putParcelableArrayListExtra("sendEnquiry",
sendEnquiry);
context.startActivity(intent);
}
});
holder1.handShakeIcon_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
companyCpsId = searchresultList.get(position)
.getCpsId();
handShakeCPSName = searchresultList.get(position)
.getCpsName();
handShakeStatus = searchresultList.get(position)
.getHandShakeStatus();
ConstantVariables.handShakeFromAdapter = true;
if (sharedpreferences.getInt("userId_sp", 0) != 0) {
if (sharedpreferences.getInt("profileActiveStatus",
0) > 0) {
if (sharedpreferences.getInt("organizationId",
0) != 0) {
if (handShakeStatus.equalsIgnoreCase("d")) {
ConstantVariables
.handShakeRequest(
context,
companyCpsId,
0,
ConstantVariables.handShakeFromAdapter,
searchResults_listView,
position);
} else if (handShakeStatus
.equalsIgnoreCase("p")) {
ConstantVariables
.handShakeRequestAccept(
context,
companyCpsId,
1,
ConstantVariables.handShakeFromAdapter,
searchResults_listView,
position,
handShakeCPSName);
}
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
context);
// Setting Dialog Title
// alertDialog.setTitle("Please Add Company");
// Setting Dialog Message
alertDialog
.setMessage("Please add your company details");
// Setting Positive "Yes" Button
alertDialog
.setPositiveButton(
"Add",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
Intent intent = new Intent(
context,
Profile_Activity.class);
context.startActivity(intent);
}
});
// Setting Negative "NO" Button
alertDialog
.setNegativeButton(
"Later",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
} else {
ConstantVariables
.requestEmailVerification(context);
}
} else {
ConstantVariables.requestLogin(context);
}
}
});
holder1.favouritesIcon_imageView
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return convertView;
}
static class ViewHolder1 {
TextView companyName_textView, companyAddress_textView,
companyLogo_textView;
ImageView handShakeIcon_imageView, favouritesIcon_imageView,
referIcon_imageView, sendEnquiry_imageView;
CheckBox chckbx1;
int id;
RelativeLayout icons_searchResultsPage_relLayout;
}
}
in your adapter getView() method set the status of the clicked checkbox in model and call notify data set changed, try that
I added the following lines with my code and it started working fine:
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
final Integer index = new Integer(position);
holder1.chckbx1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
// if checked, we add it to the list
checkedPositions.add(index);
} else if (checkedPositions.contains(index)) {
// else if remove it from the list (if it is present)
checkedPositions.remove(index);
}
}
});
// set the state of the checbox based on if it is checked or not.
holder1.chckbx1.setChecked(checkedPositions.contains(index));

checkbox auto checked item after remove item

after remove item selected check box auto check next item.
i try to override getcount method but no result
CountryAdapter.java
CountryAdapter extends ArrayAdapter<MyCountry>{
Context context; int layoutResourceId; ArrayList<MyCountry> countries; ContextualActionMode activity;
public CountryAdapter(Context context, int layoutResourceId,
ArrayList<MyCountry> countries) {
}
#Override
public int getCount() {
return countries.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final MyCountry country = countries.get(position);
ViewHolder viewHolder = null;
if(convertView == null)
{
viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(layoutResourceId, null);
viewHolder.nameEn = (TextView) convertView.findViewById(R.id.tvNameEn);
viewHolder.nameVi = (TextView) convertView.findViewById(R.id.tvNameVi);
viewHolder.flag = (ImageView) convertView.findViewById(R.id.ivFlag);
viewHolder.check = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(viewHolder);
}
else
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.nameEn.setText(countries.get(position).getNameEn());
viewHolder.nameVi.setText(countries.get(position).getNameVi());
viewHolder.flag.setImageDrawable(countries.get(position).getFlag());
viewHolder.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
count = 0;
for (MyCountry country : countries) {
if(country.isCheck()) count++;
}
if(isChecked)
{
if(activity.actionMode == null || count == 0)
activity.actionMode = activity.startActionMode(activity.callback);
count++;
country.setCheck(true);
}
else
{
country.setCheck(false);
count--;
if(count == 0) activity.actionMode.finish();
}
}
});
return convertView;
}
int count = 0;
public class ViewHolder{
TextView nameEn;
TextView nameVi;
ImageView flag;
CheckBox check;
}
ContextualActionMode.java
public class ContextualActionMode extends Activity {
ArrayList<MyCountry> countries = new ArrayList<MyCountry>();
ListView listView;
CountryAdapter adapter;
ActionMode.Callback callback = new ActionMode.Callback() {
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.mnDelete:
for (int i = 0; i < countries.size(); i++)
{
if (countries.get(i).isCheck()) {
countries.remove(countries.get(i));
countries.get(i).setChecked(false)
}
}
adapter.notifyDataSetChanged();
mode.finish();
return true;
default:
break;
}
return false;
}
};
maybe error here, i find some solutions, but nothing work
i try to change the loop, because the list start index from 0
// i can fix it, thank a lot to Armaan Stranger
link to my source for who has the same problem with me
mediafire.com/?agnvic06c69cvw0
and edit in CountryAdapter.java
viewHolder.flag.setImageDrawable(countries.get(position).getFlag());
viewHolder.check.setChecked(false); --> right here, i forgot to add set check false as default.
viewHolder.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
Try this:
Just add this line before your onCheckChanged() event like this.
viewHolder.nameEn.setText(countries.get(position).getNameEn());
viewHolder.nameVi.setText(countries.get(position).getNameVi());
viewHolder.flag.setImageDrawable(countries.get(position).getFlag());
viewHolder.check.setChecked(false);
viewHolder.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
count = 0;
for (MyCountry country : countries) {
if(country.isCheck())
count++;
}
if(isChecked)
{
if(activity.actionMode == null || count == 0)//chua co
activity.actionMode = activity.startActionMode(activity.callback);
count++;
country.setCheck(true);
}
else
{
country.setCheck(false);
count--;
if(count == 0)
activity.actionMode.finish();
}
}
});
Hope it Helps!!
You have to just set your listview before notifyDataSetChanged();
public void dellistview() {
listviewdata.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
SparseBooleanArray selected = listAdapterData.getCheckedItemPositions();
if (selected != null) {
try {
for (int i = (selected.size() - 1); i >= 0; i--)
{
if (selected.valueAt(i)) {
String str[] = arrList.get(selected.keyAt(i));
fmdbAccess.removelistitm(sourceTable, str[1]);
if (arrList != null)
arrList.remove(str);
}
}
} catch (Exception e) {
e.printStackTrace();
}
selected.clear();
arrList = fmdbAccess.getGenricTable(sourceTable, colName);
if (arrList != null && arrList.size() > 0)
setListAdapter();
listAdapterData.notifyDataSetChanged();
// finish();
}
}
Try to use android:checked="false" to CheckBox in your xml file please

How to clickable list's row and button in row in listview?

I am using a listview in my Android program.
I have row. 1) i have custom row in button and i want to when click button then open the alert box and this row clicked then open the new activity but Only one button clicked not row clicked . how to possible in this case. my code in below.
Thank you.
public class AlMessagesAdapter extends ArrayAdapter<DtoAllMessages> {
private LayoutInflater inflator;
private ArrayList<DtoAllMessages> userlist;
public AlMessagesAdapter(Activity context, ArrayList<DtoAllMessages> list) {
super(context, R.layout.custom_list, list);
this.userlist = list;
inflator = context.getLayoutInflater();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflator.inflate(R.layout.custom_list, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.tvName);
holder.date_cr = (TextView) convertView.findViewById(R.id.tvDate);
holder.img = (ImageView)convertView.findViewById(R.id.ivIcon);
holder.tokenBtn = (Button)convertView.findViewById(R.id.tokenBtn);
convertView.setTag(holder);
convertView.setTag(R.id.tvName, holder.title);
convertView.setTag(R.id.tvDate, holder.date_cr);
convertView.setTag(R.id.ivIcon,holder.img);
convertView.setTag(R.id.tokenBtn,holder.tokenBtn);
} else {
holder = (ViewHolder) convertView.getTag();
}
String token = userlist.get(position).getToken();
Log.v("MessageList", "token:" + token);
token = token.substring(0,token.length()-3);
holder.title.setText(userlist.get(position).getName()+"("+token+")");
String type_data = userlist.get(position).getType().toString();
if((type_data.equals("text")) || (type_data.equals("photo")))
{
Log.v("log", " if text photo ");
holder.date_cr.setText(userlist.get(position).getType()+":Received "+userlist.get(position).getCreated_date());
holder.tokenBtn.setVisibility(View.VISIBLE);
list.setItemsCanFocus(true);
}
else if(type_data.equals("out"))
{
Log.v("log", " else out ");
holder.date_cr.setText(userlist.get(position).getType()+":Sent "+userlist.get(position).getCreated_date());
holder.tokenBtn.setVisibility(View.GONE);
}
if(type_data.equals("text"))
{
Log.v("log", " if text ");
holder.img.setBackgroundResource(R.drawable.chatmessage);
}
else if(type_data.equals("photo"))
{
Log.v("log", " ese if photo ");
holder.img.setBackgroundResource(R.drawable.photomessage);
}
else if(type_data.equals("out"))
{
Log.v("log", " ese if out ");
holder.img.setBackgroundResource(R.drawable.outmessafe);
}
if(position%2==0)
{
convertView.setBackgroundResource(R.drawable.whitebackground);
}
else
{
convertView.setBackgroundResource(R.drawable.greybackground);
}
holder.tokenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("log_tag"," token button clicked");
}
});
return convertView;
}
class ViewHolder {
protected ImageView img;
protected TextView date_cr;
protected TextView title;
protected Button tokenBtn;
}
}
and list click event in below::
list.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
msg = userLIstArray.get(position).getMessage();
token = userLIstArray.get(position).getToken();
type = userLIstArray.get(position).getType();
int msgId = userLIstArray.get(position).getMessageid();
token = token.substring(0,token.length()-3);
int token_value = Integer.parseInt(token) * 1000;
if(type.equals("text"))
{
Log.v("log", " if in text to Display " + msg + " token "+token);
Intent i = new Intent(MessagesList.this,DisplayPopupActivity.class);
i.putExtra("msg", msg);
i.putExtra("token", token);
i.putExtra("msgid", msgId);
startActivity(i);
}
else if(type.equals("photo"))
{
Log.v("log", " else in IMage to Display " + msg + " token "+token);
Log.v("log","token "+token+" type "+type + " position "+position + "msgId "+ msgId);
Intent i = new Intent(MessagesList.this,DisplayImageActivity.class);
i.putExtra("imgData", msg);
i.putExtra("token", token);
i.putExtra("msgid", msgId);
startActivity(i);
//Log.v("log"," Message" +message);
//Toast.makeText(AllMessageActivity.this, "Message "+message, Toast.LENGTH_LONG).show();
}
return false;
}
});
}
Try this,
Instead of button use TextView. and the write onclickListerner to TextView. i had face same issue in ListView Button click using textview now its working fine. just try it.
You can add the row click event using:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, long id) {
//go to new activity
});
And the button event, as you are doing..
holder.tokenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("log_tag"," token button clicked");
//show alert
}
});
call your clickevent inside if condition
if (convertView == null) {
convertView = inflator.inflate(R.layout.custom_list, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.tvName);
holder.date_cr = (TextView) convertView.findViewById(R.id.tvDate);
holder.img = (ImageView)convertView.findViewById(R.id.ivIcon);
holder.tokenBtn = (Button)convertView.findViewById(R.id.tokenBtn);
holder.tokenBtn.setOnClickListener(click);
}
create clicklistner outside.
private OnClickListener click = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// do your stuff here
}
};
In your Adapter class set an OnclickListner
private LayoutInflater inflator;
private ArrayList<DtoAllMessages> userlist;
private Context context; //added
public AlMessagesAdapter(Activity context, ArrayList<DtoAllMessages> list) {
super(context, R.layout.custom_list, list);
this.context=context; //added
this.userlist = list;
inflator = context.getLayoutInflater();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = inflator.inflate(R.layout.custom_list, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.tvName);
holder.date_cr = (TextView) convertView.findViewById(R.id.tvDate);
holder.img = (ImageView)convertView.findViewById(R.id.ivIcon);
holder.tokenBtn = (Button)convertView.findViewById(R.id.tokenBtn);
holder.tokenBtn.setOnClickListener((OnClickListener)context); //added portion
convertView.setTag(holder);
convertView.setTag(R.id.tvName, holder.title);
convertView.setTag(R.id.tvDate, holder.date_cr);
convertView.setTag(R.id.ivIcon,holder.img);
convertView.setTag(R.id.tokenBtn,holder.tokenBtn);
} else {
holder = (ViewHolder) convertView.getTag();
}
String token = userlist.get(position).getToken();
Log.v("MessageList", "token:" + token);
token = token.substring(0,token.length()-3);
holder.title.setText(userlist.get(position).getName()+"("+token+")");
String type_data = userlist.get(position).getType().toString();
if((type_data.equals("text")) || (type_data.equals("photo")))
{
Log.v("log", " if text photo ");
holder.date_cr.setText(userlist.get(position).getType()+":Received "+userlist.get(position).getCreated_date());
holder.tokenBtn.setVisibility(View.VISIBLE);
list.setItemsCanFocus(true);
}
else if(type_data.equals("out"))
{
Log.v("log", " else out ");
holder.date_cr.setText(userlist.get(position).getType()+":Sent "+userlist.get(position).getCreated_date());
holder.tokenBtn.setVisibility(View.GONE);
}
if(type_data.equals("text"))
{
Log.v("log", " if text ");
holder.img.setBackgroundResource(R.drawable.chatmessage);
}
else if(type_data.equals("photo"))
{
Log.v("log", " ese if photo ");
holder.img.setBackgroundResource(R.drawable.photomessage);
}
else if(type_data.equals("out"))
{
Log.v("log", " ese if out ");
holder.img.setBackgroundResource(R.drawable.outmessafe);
}
if(position%2==0)
{
convertView.setBackgroundResource(R.drawable.whitebackground);
}
else
{
convertView.setBackgroundResource(R.drawable.greybackground);
}
/*holder.tokenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.v("log_tag"," token button clicked");
}
});*/
return convertView;
}
class ViewHolder {
protected ImageView img;
protected TextView date_cr;
protected TextView title;
protected Button tokenBtn;
}
}
And into your Main class
public Main extends Activity implements OnClickListener{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.casual_layout);
Button tokenBtn=(Button)findViewById(R.id.tokenBtn);
tokenBtn.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.tokenBtn:
//Write a code here to execute alertdialog
Log.d("ALERT HERE","ALERT HERE");
break;
}
}
If you want to use a Button instead of a TextView set
android:focusable="false"
to your Button

Categories

Resources