Remove item from custom listview on button click - android

I have a custom listview, that has 2 textviews and 2 buttons (play and delete button)
I want when I click the delete button to delete the current line.
My adapter class
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class SunetePreferateAdaptor extends BaseAdapter {
class ob {
String titlu, descriere;
public ob(String titlu, String descriere) {
this.titlu = titlu;
this.descriere = descriere;
}
}
ArrayList<ob> lista;
Context context;
public SunetePreferateAdaptor(Context context) {
this.context = context;
lista = new ArrayList<ob>();
for (int i = 1; i <= 20; i++) {
lista.add(new ob("text", "text2"));
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return lista.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return lista.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_favsound_row, arg2, false);
Button b2 = (Button) row.findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// here, i want to delete the current row of the listview
//
//
}
});
TextView titlu = (TextView) row.findViewById(R.id.singleText2);
titlu.setText(lista.get(arg0).titlu);
titlu.setTextColor(Color.WHITE);
titlu.setTypeface(Global.font1);
TextView descriere = (TextView) row.findViewById(R.id.singleText1);
descriere.setText(lista.get(arg0).descriere);
descriere.setTextColor(Color.WHITE);
descriere.setTypeface(Global.font1);
return row;
}
}
Well how can I do that?
I've tried making the arraylist static and delete its items on click.. but no success..

You need not make ArrayList static.
You need to delete the data from the list which populates listview. You call notifyDataSetChanged(); to refresh the lsitview.
You can remove the static key word and use
Button b2 = (Button) row.findViewById(R.id.button1);
b2.setTag(arg0);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
int pos = (int)arg0.getTag();
lista.remove(pos);
SunetePreferateAdaptor.this.notifyDataSetChanged(); }
});
Alternative :
You can pass the list to the constructor of adapter class.
ListView lv = (ListView) this.findViewById(R.id.listView1);
ArrayList<ob> lista = new ArrayList<ob>();
for (int i = 1; i <= 20; i++) {
lista.add(new ob("text", "text"+i));
}
lv.setAdapter(new SunetePreferateAdaptor(this,lista));
Then have this in a separate .java file
class ob {
String titlu, descriere;
public ob(String titlu, String descriere) {
this.titlu = titlu;
this.descriere = descriere;
}
}
Then
public class SunetePreferateAdaptor extends BaseAdapter {
ArrayList<ob> lista;
Context context;
public SunetePreferateAdaptor(Context context, ArrayList<ob> lista ) {
this.context = context;
this.lista= lista;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return lista.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return lista.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.fg, arg2, false);
Button b2 = (Button) row.findViewById(R.id.button1);
b2.setTag(arg0);
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
int pos = (int)arg0.getTag();
lista.remove(pos);
SunetePreferateAdaptor.this.notifyDataSetChanged(); }
});
TextView titlu = (TextView) row.findViewById(R.id.textView1);
titlu.setText(lista.get(arg0).titlu);
titlu.setTextColor(Color.WHITE);
TextView descriere = (TextView) row.findViewById(R.id.textView2);
descriere.setText(lista.get(arg0).descriere);
return row;
}
}

try this
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
lista.remove(position);
SunetePreferateAdaptor.notifyDataSetChanged();
}
});

You can done it by using your ArrayList lista. First remove the item in current position and the call adapter.notifyDataSetChanged() function.

This code worked absolutely fine for me.
public class CustomAdapter extends ArrayAdapter<String>
{
Context c1;
String s1[];
int s2[];
CustomAdapter(Context c,String s[],int s3[])
{
super(c,R.layout.tcustom,s);
this.c1=c;
this.s1=s;
this.s2=s3;
}
public View getView(int position,View v,ViewGroup parent)
{
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v=li.inflate(R.layout.tcustom,null);
TextView tv=(TextView)v.findViewById(R.id.textView);
ImageView im=(ImageView)v.findViewById(R.id.imageview);
tv.setText(s1[position]);
im.setImageResource(s2[position]);
Button bt = (Button) v.findViewById(R.id.button);
bt.setTag(position); //important so we know which item to delete on button click
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
v.setVisibility(View.GONE);
notifyDataSetChanged();
int positionToRemove = (int)v.getTag(); //get the position of the view to delete stored in the tag
removeItem(positionToRemove); //remove the item
}
});
return v;
}
public void removeItem(int position){
//convert array to ArrayList, delete item and convert back to array
ArrayList<String> a = new ArrayList<>(Arrays.asList(s1));
a.remove(position);
String[] s = new String[a.size()];
s=a.toArray(s);
s1 = s;
notifyDataSetChanged(); //refresh your listview based on new data
}
public int getCount() {
return s1.length;
}
public String getItem(int position) {
return s1[position];
}}

Related

ListView remember only the position of old list after Filtering

i created an app that show a listview with clickable items. i have an edit text to make the search. everything is working great but when im searching for an item, the app give my a new list, the probleme is when im clicking on any item on thisnew list items it redirect me to the link of the item in old list.here is my code:
-For ReaderListAdapter.java :
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ReaderListAdapter extends BaseAdapter {
private List<Reader> listReader = null;
LayoutInflater layoutInflater;
Context context;
private int lastPosition = -1;
// constructeur
public ReaderListAdapter(Context context, List<Reader> listFood) {
this.listReader = listFood;
layoutInflater = LayoutInflater.from(context);
this.listReader = listFood;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listReader.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listReader.get(position);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
static class ViewHolder {
TextView nomView;
TextView priceView;
ImageView pictureView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.reader_row, null);
holder = new ViewHolder();
// initialisation des vues
holder.nomView = (TextView) convertView.findViewById(R.id.name);
holder.priceView = (TextView) convertView.findViewById(R.id.price);
holder.pictureView = (ImageView) convertView
.findViewById(R.id.picture);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// affchier les données convenablement dans leurs positions
holder.nomView.setText(listReader.get(position).getName());
holder.priceView.setText(String.valueOf(listReader.get(position)
.getPrice()));
holder.pictureView.setBackgroundDrawable(listReader.get(position).getPicture());
// changer R.anim.ton_effet
Animation animation = AnimationUtils.loadAnimation(context,
(position > lastPosition) ? R.anim.up_from_bottom
: R.anim.up_from_bottom);
convertView.startAnimation(animation);
lastPosition = position;
return convertView;
}}
For MainActivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
String[] listNames = { "site1", "site2", "site3"};
int[] listPrices = { 1, 2, 3};
ArrayList<Reader> listReader;
ListView lv;
EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listReader);
search = (EditText) findViewById(R.id.search);
Drawable[] listPictures = {
getResources().getDrawable(R.drawable.a1),
getResources().getDrawable(R.drawable.a2),
getResources().getDrawable(R.drawable.a3)};
listReader = new ArrayList<Reader>();
for (int i = 0; i < listPictures.length; i++) {
listReader.add(new Reader(i + 1, listNames[i], listPictures[i],
listPrices[i]));
}
lv.setAdapter(new ReaderListAdapter(getApplicationContext(), listReader));
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
filtrer();
} });
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent=new Intent(MainActivity.this,WebActivity.class);
switch (position) {
case 0:
intent.setData(Uri.parse("http://www.google.com")) ;break;
case 1:
intent.setData(Uri.parse("http://www.yahoo.com")) ;break;
case 2:
intent.setData(Uri.parse("http://www.quranf.com")) ;break;
}
if (intent != null) {
startActivity(intent);
}} });}
public void filtrer() {
// retourner la chaine saisie par l'utilisateur
String name = search.getText().toString();
// créer une nouvelle liste qui va contenir la résultat à afficher
final ArrayList<Reader> listReaderNew = new ArrayList<Reader>();
for (Reader reader : listReader) {
// si le nom du food commence par la chaine saisie , ajouter-le !
if (reader.getName().toLowerCase().toString().contains(name)) {
listReaderNew.add(reader);
}
}
// vider la liste
lv.setAdapter(null);
if (listReaderNew.size() == 0) {
listReaderNew.add(new Reader(100, "Pas d'élements.. réessayer !",
getResources().getDrawable(R.drawable.error), 0));
}
// ajouter la nouvelle liste
lv.setAdapter(new ReaderListAdapter(getApplicationContext(), listReaderNew));
}}
Any help would be appreciated from you. thank you If you need any clarification plz let me know
public class ReaderListAdapter extends BaseAdapter {
private List<Reader> listReader = null;
LayoutInflater layoutInflater;
Context context;
private int lastPosition = -1;
ArrayList<Reader> arrayList;
// constructeur
public ReaderListAdapter(Context context, List<Reader> listFood) {
this.listReader = listFood;
layoutInflater = LayoutInflater.from(context);
this.listReader = listFood;
this.context = context;
this.arrayList=listFood;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listReader.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listReader.get(position);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
static class ViewHolder {
TextView nomView;
TextView priceView;
ImageView pictureView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.reader_row, null);
holder = new ViewHolder();
// initialisation des vues
holder.nomView = (TextView) convertView.findViewById(R.id.name);
holder.priceView = (TextView) convertView.findViewById(R.id.price);
holder.pictureView = (ImageView) convertView
.findViewById(R.id.picture);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// affchier les données convenablement dans leurs positions
holder.nomView.setText(listReader.get(position).getName());
holder.priceView.setText(String.valueOf(listReader.get(position)
.getPrice()));
holder.pictureView.setBackgroundDrawable(listReader.get(position).getPicture());
// changer R.anim.ton_effet
Animation animation = AnimationUtils.loadAnimation(context,
(position > lastPosition) ? R.anim.up_from_bottom
: R.anim.up_from_bottom);
convertView.startAnimation(animation);
lastPosition = position;
return convertView;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
listFood.clear();
if (charText.length() == 0) {
listFood.addAll(arraylist);
} else {
for (Reader cp : arraylist) {
if (cp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
listFood.add(cp);
}
}
}
notifyDataSetChanged();
}
}
*******************your MainActivity**********************
public class MainActivity extends Activity {
String[] listNames = { "site1", "site2", "site3"};
int[] listPrices = { 1, 2, 3};
ArrayList<Reader> listReader;
ListView lv;
EditText search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listReader);
search = (EditText) findViewById(R.id.search);
Drawable[] listPictures = {
getResources().getDrawable(R.drawable.a1),
getResources().getDrawable(R.drawable.a2),
getResources().getDrawable(R.drawable.a3)};
listReader = new ArrayList<Reader>();
for (int i = 0; i < listPictures.length; i++) {
listReader.add(new Reader(i + 1, listNames[i], listPictures[i],
listPrices[i]));
}
ReaderListAdapter readerListAdapternew ReaderListAdapter(getApplicationContext(), listReader)
lv.setAdapter(readerListAdapternew);
search.addTextChangedListener(new TextWatcher() {
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
String text = search.getText().toString()
.toLowerCase(Locale.getDefault());
readerListAdapternew .filter(text);
} });
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent=new Intent(MainActivity.this,WebActivity.class);
switch (position) {
case 0:
intent.setData(Uri.parse("http://www.google.com")) ;break;
case 1:
intent.setData(Uri.parse("http://www.yahoo.com")) ;break;
case 2:
intent.setData(Uri.parse("http://www.quranf.com")) ;break;
}
if (intent != null) {
startActivity(intent);
}} });}
}

How to update values in database using an update image button in custom list adapter?

This is my custom list adapter. I want to update the values in table using the update ImageButton in the list. On clicking it, the old values should be shown in a new activity and then the edited value must be stored in the database. However, I am unable to pass an intent inside the onClick() method.
Please suggest me a solution
public class CustomListAdapter extends BaseAdapter implements ListAdapter
{
private ArrayList<String> list = new ArrayList<String>();
private Context context;
OnItemSelectedListener onItemSelectedListener;
public int pos;
String pass,pass2,edit,epass;
public CustomListAdapter(List list, Context context) {
this.list = (ArrayList<String>) list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
//pass2 = list.toString();
return list.get(pos);
}
//#Override
//public Long getItemId(int pos) {
//
// //just return 0 if your list items do not have an Id variable.
//}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_custom_list, null);
}
//Handle TextView and display string from your list
final TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
ImageButton deleteBtn = (ImageButton)view.findViewById(R.id.delete_btn);
ImageButton editBtn = (ImageButton)view.findViewById(R.id.edit_btn);
//Button addBtn = (Button)view.findViewById(R.id.add_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position);
pass = listItemText.getText().toString();
notifyDataSetChanged();
pass2 = pass.substring(0,pass.indexOf(' '));
System.out.println(pass2);
Moneydb.delete(pass2);
}
});
editBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v2) {
// TODO Auto-generated method stub
edit=listItemText.getText().toString();
epass = listItemText.getText().toString();
edit = epass.substring(0,epass.indexOf(' '));
Moneydb.edit(edit);
}
});
return view;
}
protected Context getContext() {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
//return list.get(position).getId();
return 0;
}
public void clear() {
//CustomListAdapter collection = null;
// TODO Auto-generated method stub
list.clear();
notifyDataSetChanged();
}
I suggest you to assign and ContextMenu to your list view with two MenuItem, Edit and Delete and write associated code outside of adapter
or you can start Activity by :
Intent new_intent = new Intent(v.getRootView().getContext(),edit_activity.class);
new_intent.putExtra("Key","Value");
v.getRootView().getContext().startActivity(new_intent);
i think the first method is best ;)

How to set radiobutton unchecked in adapter class

I have a customdialog box ,in this i have a listview and a spinner item.The listview contains textview and a radio button in each row.I can select only one row at a time with the help of radio buttons.This is happening.
Problem is coming when i select spinner items and then i select radio button ,the previous radio button is still selected.Now what i want when i select spinner items ,the previously selected radiobuttons should be unchecked.
Note:my spinner is in Main class and radio button is in CustomAdapterClass which i am calling in my Main class
Here is my code: Adapter Class:
public class APTRequestCustomAdapter extends BaseAdapter{
Context context;
ArrayList<APTRequestCustomdetails> APTRequestCustomitems;
private static String display_aptstatus1="";
public static String adapterbookingid="";
private boolean userSelected = false;
public static RadioButton mCurrentlyCheckedRB;
String patientid1="";
public static String from2="";
public static String to2="";
public static String testing2="";
public static String cancelbookid="";
public static String radiostring="";
public static String troubleradiobutton="";
private int selectedItemIndex=-1;
public APTRequestCustomAdapter(Context context,
ArrayList<APTRequestCustomdetails> aPTRequestCustomitems) {
super();
this.context = context;
this.APTRequestCustomitems = aPTRequestCustomitems;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return APTRequestCustomitems.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return APTRequestCustomitems.get(arg0);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v=convertView;
final int pos=position;
if(v==null){
v = LayoutInflater.from(context).inflate(R.layout.backupcustomdailoguniversalappointment,null);
}
TextView patientname=(TextView)v.findViewById(R.id.txtpatientname);
TextView tag=(TextView)v.findViewById(R.id.txttype);
TextView phone=(TextView)v.findViewById(R.id.txtphone);
TextView age=(TextView)v.findViewById(R.id.txtage);
TextView Apptstatus=(TextView) v.findViewById(R.id.txtapptstatus);
TextView bookid=(TextView) v.findViewById(R.id.txtbookingid);
ImageView remove=(ImageView)v.findViewById(R.id.txtremove);
RadioButton radio=(RadioButton)v.findViewById(R.id.txtRadiobutton);
patientname.setPaintFlags(patientname.getPaintFlags() |Paint.UNDERLINE_TEXT_FLAG);
patientname.setText(APTRequestCustomitems.get(position).getPatient_Name());
tag.setText(APTRequestCustomitems.get(position).getTag());
phone.setText(APTRequestCustomitems.get(position).getPhone());
age.setText(APTRequestCustomitems.get(position).getAge());
Apptstatus.setText(APTRequestCustomitems.get(position).getAppointmentstatus());
bookid.setText(APTRequestCustomitems.get(position).getBookingId());
Apptstatus.setVisibility(View.INVISIBLE);
bookid.setVisibility(View.INVISIBLE);
//APT_CustomRequestResponse.radiostring="";
// adapterbookingid=APTRequestCustomitems.get(pos).getBookingId().toString();// wrong code
patientname.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("Hello buddy");
Intent io=new Intent(context, PatientSummaryActivity.class);
DoctorGlobal.patid=APTRequestCustomitems.get(pos).getPatient_ID();
DoctorGlobal.patname=APTRequestCustomitems.get(pos).getPatient_Name();
System.out.println("PATID"+DoctorGlobal.patid);
context.startActivity(io);
}
});
if (position==getCount()-1 && userSelected==false) {
// radio.setChecked(true);
mCurrentlyCheckedRB = radio;
} else {
radio.setChecked(false);
}
if(APTRequestCustomitems.get(position).getAppointmentstatus().equals("1")){
remove.setVisibility(View.INVISIBLE);
radio.setVisibility(View.INVISIBLE);
v.setBackgroundColor(Color.parseColor("#1569C7"));
}else
{
v.setBackgroundColor(Color.parseColor("#FFFFFF"));
remove.setVisibility(View.VISIBLE);
radio.setVisibility(View.VISIBLE);
radio.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
APTRequestCustomAdapter.radiostring="checkedtrue";
if (mCurrentlyCheckedRB !=null) {
if (mCurrentlyCheckedRB ==null)
mCurrentlyCheckedRB = (RadioButton) v;
mCurrentlyCheckedRB.setChecked(true);
// Toast.makeText(context, ""+pos, Toast.LENGTH_LONG).show();
adapterbookingid=APTRequestCustomitems.get(pos).getBookingId().toString();
}
if (mCurrentlyCheckedRB == v)
return;
mCurrentlyCheckedRB.setChecked(false);
((RadioButton) v).setChecked(true);
mCurrentlyCheckedRB = (RadioButton) v;
}
});
}
return v;
}
}
And this is the code where i am calling the adapter class:
This method is in Async Class on PostExecute()method
public void showCustomDialog() {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(context);
List<String> list=new ArrayList<String>();
list.add("Normal");
list.add("Low");
list.add("High");
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.customdialoguniversalappointment);
ListView listcustomuniversalappt=(ListView) dialog.findViewById(R.id.listcustomuniversalappt);
LinearLayout layoutsubject=(LinearLayout) dialog.findViewById(R.id.layoutsubject);
LinearLayout layoutappt=(LinearLayout) dialog.findViewById(R.id.layoutappt);
spinnerappt=(Spinner)dialog.findViewById(R.id.permissionspinner);
ImageView cancel=(ImageView)dialog.findViewById(R.id.imgcancel);
Button cancelappt=(Button)dialog.findViewById(R.id.btncancelappt);
Button confirmappt=(Button)dialog.findViewById(R.id.btnconfirmappt);
EditText subject=(EditText) dialog.findViewById(R.id.edtsubject);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerappt.setAdapter(dataAdapter);
spinnerappt.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
int index = arg0.getSelectedItemPosition();
selected_item=arg0.getItemAtPosition(arg2).toString();
APTRequestCustomAdapter.mCurrentlyCheckedRB.setChecked(false);//this line of code is not executing,the radio button remains checked in the view
if(APTRequestCustomAdapter.mCurrentlyCheckedRB.isChecked()){// this lines of codes are not executing even though the radio button is checked ,i don't know why
APTRequestCustomAdapter.mCurrentlyCheckedRB.setChecked(false);// And this line is also not executing
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
APTRequestCustomAdapter adap=new APTRequestCustomAdapter(context,run_custom_universal_apptdata());
listcustomuniversalappt.setAdapter(adap);
/*//runapptstatus_method();
listcustomuniversalappt.setChoiceMode(1);
/
dialog.show();
}
Try to use your Custom Adapter like,
public class MyRadioAdapter extends BaseAdapter
{
private Context mContext;
private ArrayList<Variation> mVariations;
private int mSelectedVariation;
public MyRadioAdapter(Context context, ArrayList<Variation> variations, int selectedVariation)
{
mContext = context;
mVariations = variations;
mSelectedVariation = selectedVariation;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view = convertView;
if(view==null)
{
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.my_radio_adapter_item, null);
}
final Variation variation = mVariations.get(position);
TextView name = (TextView) view.findViewById(R.id.name);
RadioButton radio = (RadioButton) view.findViewById(R.id.radio);
name.setText(variation.getName());
if(position==mSelectedVariation) radio.setChecked(true);
else radio.setChecked(false);
view.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
mSelectedVariation = position;
MyRadioAdapter.this.notifyDataSetChanged();
}
});
return view;
}
here Radio buttons are usually grouped by Radio Group.When one RadioButton within a group is selected, all others are automatically deselected.

Progress dialog not showing in button click event in listview

I have a button in each list item of list view. In that button click event i have some codes to run. In click event im showing the progress dialog before the code runs. but its not getting shown. After all the codes in click event completes in the end progress dialog gets shown. Plz help me.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
TheListViewM = (ListView) findViewById(R.id.lvItems);
ImageAdapter anImageAdapterM =new ImageAdapter(this);
TheListViewM.setAdapter(anImageAdapterM);
}
public class ImageAdapter extends BaseAdapter {
private Context mContextL;
public ImageAdapter(Context contextP) {
mContextL = contextP;
}
public int getCount() {
return ItemList.GetLength();
}
public Object getItem(int PositionP) {
return ItemList.GetObject(PositionP);
}
public long getItemId(int PositionP) {
return PositionP;
}
public View getView(final int PositionP, View ConvertViewP, ViewGroup ParentP) {
if (ConvertViewP == null) {
LayoutInflater inflater = (LayoutInflater) mContextL.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ConvertViewP = inflater.inflate(R.layout.add_cart_row_layout, ParentP, false);
}
TextView textView1 = (TextView) ConvertViewP.findViewById(R.id.tvName);
textView1.setText("asdfg");
final Spinner spQuantity = (Spinner) ConvertViewP.findViewById(R.id.spQuantity);
spQuantity.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> Parent, View view,
int pos, long id) {
ProgressDialog aProgressDialogL = new ProgressDialog(mContextL);
aProgressDialogL.setMessage("Loading...");
aProgressDialogL.show();
//Processiing codes
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
ArrayAdapter<String> QuantityAdapter1 = new ArrayAdapter<String>(mContextL,android.R.layout.simple_spinner_item, QuantityList);
QuantityAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spQuantity.setAdapter(QuantityAdapter1);
Button btn1 = (Button) ConvertViewP.findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ProgressDialog aProgressDialogL = new ProgressDialog(activity1.this);
aProgressDialogL.setMessage("Loading...");
aProgressDialogL.show(); }
});
return ConvertViewP;
}
Try this one.
public class ImageAdapter extends BaseAdapter {
private Context mContextL;
public ImageAdapter(Context contextP) {
mContextL = contextP;
}
public int getCount() {
return ItemList.GetLength();
}
public Object getItem(int PositionP) {
return ItemList.GetObject(PositionP);
}
public long getItemId(int PositionP) {
return PositionP;
}
class ViewHolder {
Button btn1;
TextView textView1;
Spinner spQuantity;
}
public View getView(final int PositionP, View ConvertViewP, ViewGroup ParentP) {
ViewHolder holder;
if (ConvertViewP == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContextL.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ConvertViewP = inflater.inflate(R.layout.add_cart_row_layout, ParentP, false);
holder.textView1 = (TextView) ConvertViewP.findViewById(R.id.tvName);
holder.spQuantity = (Spinner) ConvertViewP.findViewById(R.id.spQuantity);
holder.btn1 = (Button) ConvertViewP.findViewById(R.id.btn1);
ConvertViewP.setTag(holder);
}
else{
holder = (ViewHolder) ConvertViewP.getTag();
}
holder.textView1.setText("asdfg");
holder.spQuantity.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> Parent, View view,
int pos, long id) {
ProgressDialog aProgressDialogL = new ProgressDialog(mContextL);
aProgressDialogL.setMessage("Loading...");
aProgressDialogL.show();
//Processiing codes
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
ArrayAdapter<String> QuantityAdapter1 = new ArrayAdapter<String>(mContextL,android.R.layout.simple_spinner_item, QuantityList);
QuantityAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spQuantity.setAdapter(QuantityAdapter1);
holder.btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ProgressDialog aProgressDialogL = new ProgressDialog(activity1.this);
aProgressDialogL.setMessage("Loading...");
aProgressDialogL.show(); }
});
return ConvertViewP;
}
}

Dynamic ListView - Refresh on Button Click

Android 2.3.3
I have seen few questions at stackoverflow, regarding refreshing the listview. But none of them worked for me.
I have a dynamic listview and I have a button inside it. The data is being populated from database and each listview row is a custom layout. On press of the (Clear) button, the database is cleared(which works fine) and the listview should get refreshed(the part to be figured out).
Below is the code...
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.mobilevoiceapps.advancedvoicecalculatorfree.R;
public class History extends ListActivity {
ListView lvHistory;
ArrayAdapter<String> adHistory;
ArrayList<String> alHistoryCopy = new ArrayList<String>();
String[] emptyList = { "Your Calculations History is Empty. Please Perform Some Calculations and visit again." };
Database db;
Cursor c;
String expression = "";
String result = "";
boolean isEmpty = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// setContentView(R.layout.history);
lvHistory = getListView();
final MyCustomAdapter myad = new MyCustomAdapter();
db = new Database(this);
c = db.retrieve_history();
if (!((c.moveToFirst()) || c.equals(null) || c.getCount() == 0)) {
} else if (c.getCount() > 0) {
c.moveToFirst();
}
LayoutInflater header = getLayoutInflater();
View header_View = header.inflate(R.layout.history_header, null);
lvHistory.addHeaderView(header_View);
View second_Header_View = header.inflate(
R.layout.history_second_header, null);
lvHistory.addHeaderView(second_Header_View);
Button btnClearHistory = (Button) second_Header_View
.findViewById(R.id.btnClearHistory);
btnClearHistory.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.clear_history();
myad.notifyDataSetChanged();
lvHistory.invalidateViews();
lvHistory.refreshDrawableState();
}
});
lvHistory.setAdapter(myad);
}
class MyCustomAdapter extends BaseAdapter {
#Override
public int getCount() {
// TODO Auto-generated method stub
return c.getCount();
}
#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;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
HistoryViewHolder viewHolder;
if (convertView == null) {
LayoutInflater li = getLayoutInflater();
convertView = li.inflate(R.layout.history_row, null);
viewHolder = new HistoryViewHolder();
viewHolder.txtcnt = (TextView) convertView
.findViewById(R.id.txtView_History_Count);
viewHolder.txtexp = (TextView) convertView
.findViewById(R.id.txtView_History_Expression);
viewHolder.txtres = (TextView) convertView
.findViewById(R.id.txtView_History_Result);
convertView.setTag(viewHolder);
} else {
viewHolder = (HistoryViewHolder) convertView.getTag();
}
viewHolder.txtcnt.setText(String.valueOf(position + 1));
System.out.println("Position"
+ viewHolder.txtcnt.getText().toString());
c.moveToPosition(position);
expression = c.getString(c.getColumnIndex("expression"));
result = c.getString(c.getColumnIndex("result"));
viewHolder.txtexp.setText(expression);
System.out.println("Expression"
+ viewHolder.txtexp.getText().toString());
viewHolder.txtres.setText(result);
System.out.println("Result"
+ viewHolder.txtres.getText().toString());
return convertView;
}
public class HistoryViewHolder {
TextView txtcnt;
TextView txtexp;
TextView txtres;
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (db != null) {
db.close();
}
if (c != null) {
c.close();
}
}
}
EDIT ::: With ScreenShots :::
Try to extend your MyCustomAdapter from BaseAdapter and use notifyDataSetChanged to refresh ListView.
The better way to display database content is CursorAdapter (or CursorLoader) - such adapters listen for update notifications and reloads the content automatically.
try this, You need to refresh you ListView after delete one item using myad.notifyDataSetChanged();
btnClearHistory.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
YourActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
myad.notifyDataSetChanged();
}
});
}
});
Try add c = db.retrieve_history(); after db.clear_history();.
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.clear_history();
c = db.retrieve_history();
myad.notifyDataSetChanged();
lvHistory.invalidateViews();
lvHistory.refreshDrawableState();
}
Hope this helped you.
Just restart your activity..
ActivityName.this.finish();
Intent intent=new Intent(this, ActivityName.class);
startActivity(intent);
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_loja, container, false);
listatividade = (ListView) view.findViewById(R.id.listservico);
String[] valueatividade = new String[] { "atividade 1",
"atividade 2",
"atividade 3" };
adapteratividade = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, valueatividade);
listatividade.setAdapter(adapteratividade);
listaatividade.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
int itemPosition = position;
String itemValue = (String) listaatividade.getItemAtPosition(position);
Toast.makeText(getActivity(), "Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG) .show();
updateData();
}
});
return view;
}
private void updateData() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
String[] valueatividade = new String[] { "atividade 4", "atividade 5", "atividade 6" };
adapteratividade = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1, android.R.id.text1, valueatividade);
listatividade.setAdapter(adapteratividade);
}
});
}

Categories

Resources