How to update the checkbox items position - android

I am using the check box in ListActivity.I doesn't know how to update the checkbox in server.
Now I came up with the result for checked item is unchecked and save means it will save(or update) the server.But in unchecked item checked means not save(or not update) the server.
Rsvp_EngagementMeals.java:
public class Rsvp_EngagementMeals extends ListActivity
{
#Override
checkstatus=new Hashtable<Integer,String>();
status=new ArrayList<String>();
veg =Rsvp_Meals.veg;
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/mmealitems.aspx?uname="+LoginForm.str1+"&occasion="+occasionval;
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
if (result != null)
{
token = new StringTokenizer2(result, "");
}
value = new ArrayList<String>();
while (token.hasMoreTokens())
{
value.add(token.nextToken());
}
value.add(Integer.toString(value.size()));
Integer k=null;
table=new Hashtable<Integer,ArrayList<String>>();
itemId = new ArrayList<String>();
str2 = new ArrayList<String>();
str3 = new ArrayList<String>();
stritem = new ArrayList<String>();
vegitems = new ArrayList<String>();
int id=0,c=0,n=value.size();
for(int j=0; j<n; j++)
{
z = value.get(j);
String[] mystring = z.split("<br>");
int arraysize = mystring.length;
for(int a=0; a<arraysize-1;a++)
{
str2.add(mystring[0]);
}
}
for(int g=0; g<str2.size();g++)
{
String name = str2.get(g);
token2 = new StringTokenizer2(name, "|", false);
while (token2.hasMoreTokens())
{
vegitems.add(token2.nextToken());
}
}
for(int x=1;x<vegitems.size();x++)
{
itemId.add(vegitems.get(x));
x=x+1;
stritem.add(vegitems.get(x));
x=x+1;
status.add(vegitems.get(x));
}
setListAdapter(new IconicAdapter(this));
save.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tru = new StringBuffer();
fals = new StringBuffer();
for (int i = 0; i<status.size();i++)
{
if (status.get(i).equals("True"))
tru.append(itemId.get(i)+",");
}
boolean netvalue = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
netvalue = true;
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/version21/minsertmealchoiceNew.aspx?uname=abcdefg&occasion=Engagement
"&choice="+tru+"&ownchoice=&category=";
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
StringTokenizer st = new StringTokenizer(result, "|");
result = st.nextToken();
if ((result.equals("Engagement 1&")) || (result.equals("Wedding 1&")) || (result.equals("Reception 1&")))
{
// alertbox("Success", "saved successfully");
Dialog locationError = new AlertDialog.Builder(Rsvp_EngagementMeals.this)
.setIcon(0)
.setMessage("Meals has been saved sucessfully")
.setTitle("Success")
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int id) {
Intent ma = new Intent(
Rsvp_EngagementMeals.this, Rsvp_Meals.class);
startActivity(ma);
finish();
}
}).create();
locationError.show();
} else
alertbox("", result);
} else {
alertbox("Message", "No Internet Connection!");
}
}
});
}// End of On create method
#Override
protected void onListItemClick(ListView parent, View v, int position,long id)
{
super.onListItemClick(parent, v, position, id);
}
public void onClick(View v)
{
System.out.println("On View Click");
}
#SuppressWarnings("rawtypes")
class IconicAdapter extends ArrayAdapter
{
Activity context;
#SuppressWarnings("unchecked")
IconicAdapter(Activity context)
{
super(context, R.layout.rsvp_mealsse, stritem);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View row = inflater.inflate(R.layout.rsvp_mealsse,null);//viewappointlist, null);
TextView index = (TextView) row.findViewById(R.id.index);
index.setText(String.valueOf(position+1)+".");
TextView label = (TextView) row.findViewById(R.id.title);
label.setText(stritem.get(position));
CheckBox check=(CheckBox)row.findViewById(R.id.check);
check.setId(Integer.parseInt(itemId.get(position)));
if(status.get(position).equals("True"))
check.setChecked(true);
;
check.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int ind=itemId.indexOf(String.valueOf(buttonView.getId()));
status.set(ind, String.valueOf(isChecked));
}
});
return (row);
}
}
This is my full code.How to change the status in check box.I want result for when I update the check box its save the server and after I view the list the updated item view my checkbox.

The only bug that i could point was the spelling of false in your if statement:
Change this code:
if(status.get(position).equals("False"))
To this code:
if(status.get(position).equals("false"))
hope this works!

Related

ListView lost focus

I am working on an app in android studio.
My app has a listview, whiche has Edittext , textview and checkbox in its row.
my proplem is when I have more than five items in my listvew, the listview lost focus, for example: when I press on checkbox on the 6th item , the textview shows me the name from the first item.
I wish I could explain my proplem very well.
This is my adapter:
public AdapterListView(Context context, int resource, ArrayList<ObjectPeople> arraypeople) {
super(context, resource);
this.mContext = context;
this.arrayPeople = arraypeople;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, null);
holder = new ViewHolder();
holder.mission_name = (TextView) convertView.findViewById(R.id.mission_name);
holder.mission_time = (TextView) convertView.findViewById(R.id.mission_time);
holder.edit_time = (EditText) convertView.findViewById(R.id.edit_time);
holder.mission_image= (ImageView) convertView.findViewById(R.id.mission_image);
holder.cbm = (CheckBox) convertView.findViewById(R.id.checkbo);
convertView.setTag(holder);
holder.cbm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v ) {
CheckBox cb = (CheckBox) v ;
final ObjectPeople person = arrayPeople.get(position);
if(cb.isChecked()) {
arrayPeople.get(position).checkbox= true;
int mis_tm=0;
try{ mis_tm= Integer.parseInt( holder.edit_time.getText().toString());}
catch (Exception e){
cb.setChecked(false);
Toast.makeText(mContext, "يرجى إدخال قيمة معينة", Toast.LENGTH_SHORT).show();}
person.time= mis_tm;
if(mis_tm>0&&mis_tm<1200){
holder.mission_name.setText("اسم المهمة: "+person.name);
holder.mission_time.setText( "مدة المهمة: "+ person.time );
holder.edit_time.setVisibility(View.GONE);}
else{
cb.setChecked(false);
Toast.makeText(mContext, "يرجى اختيار رقم حقيقي", Toast.LENGTH_SHORT).show();
}
}
else {
arrayPeople.get(position).checkbox= false;
holder.edit_time.setVisibility(View.VISIBLE);
}
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
final ObjectPeople person = arrayPeople.get(position);
holder.mission_name.setText("اسم المهمة: "+person.name);
holder.mission_time.setText( "مدة المهمة: ");
holder.mission_image.setImageResource(arrayPeople.get(position).image);
holder.edit_time.setId(position);
holder.edit_time.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
try {
if (!hasFocus) {
final int position = v.getId();
final EditText Caption = (EditText) v;
arrayPeople.get(position).time = Integer.parseInt(Caption.getText().toString());
}
}catch (Exception e){}
}
});
holder.cbm.setTag(arrayPeople);
return convertView;
}
#Override
public int getCount() {
return arrayPeople.size();
}
static class ViewHolder {
TextView mission_name;
TextView mission_time;
EditText edit_time;
ImageView mission_image;
CheckBox cbm;
}
}
and this select.java which contains the arraylist and list view:
public class select extends AppCompatActivity {
ArrayList<ObjectPeople> arrPeople;
ListView lvPeople;
AdapterListView adapter;
ObjectPeople person;
SharedPreferences settings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select);
settings = getApplicationContext().getSharedPreferences("shared", 0);
lvPeople= (ListView) findViewById(R.id.lvPeopl);
arrPeople=new ArrayList<>();
person = new ObjectPeople("حفظ قرآن", 0,false, R.drawable.quran_hifz_r);
arrPeople.add(person);
person = new ObjectPeople("تلاوة قرآن", 0 ,false,R.drawable.img);
arrPeople.add(person);
person = new ObjectPeople("قراءة كتاب", 0 , false,R.drawable.books_r);
arrPeople.add(person);
person = new ObjectPeople("دورات تطوير مهارات", 0 , false,R.drawable.courses_r);
arrPeople.add(person);
person = new ObjectPeople("رياضة", 15 , false,R.drawable.sport_r);
arrPeople.add(person);
final String[] misson_name = new String[1];
Button adf= (Button) findViewById(R.id.add_mission_out_btn);
adf.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View view = LayoutInflater.from(select.this).inflate(R.layout.add_mission_lyt,null);
final EditText add_name = (EditText) view.findViewById(R.id.add_mission_name);
AlertDialog.Builder builder = new AlertDialog.Builder(select.this);
builder.setMessage("add your mission")
.setView(view)
.setPositiveButton("إضافة", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
misson_name[0] = add_name.getText().toString();
arrPeople.add(new ObjectPeople(misson_name[0], 0, true,R.drawable.smile_small_r));
}
})
.setNegativeButton("إلغاء",null)
.setCancelable(false);
AlertDialog alert =builder.create();
alert.show();
}
});
adapter=new AdapterListView(this,R.layout.item_listview,arrPeople);
lvPeople.setAdapter(adapter);
checkButtonClick();
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.btn_save);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getApplicationContext().getSharedPreferences("shared", 0);
int hours2=settings.getInt("hours",0)*60;
ArrayList<ObjectPeople> selected_missions = new ArrayList<>();
int missoins_time_calc=0;
for (int i = 0; i <arrPeople.size(); i++) {
if(arrPeople.get(i).checkbox==true){
selected_missions.add(arrPeople.get(i));
missoins_time_calc= missoins_time_calc + arrPeople.get(i).time;}
}
if (hours2 == missoins_time_calc){
Gson gson = new Gson();
String jsonText = gson.toJson(selected_missions);
SharedPreferences.Editor editor = settings.edit();
editor.putString("selected_array", jsonText);
editor.commit();
Intent intent = new Intent(select.this, yourprogram.class);
startActivity(intent);
overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
}
else if (hours2 > missoins_time_calc){
Toast.makeText(select.this, "بقي"+(-missoins_time_calc+ hours2)+" دقيقة ", Toast.LENGTH_SHORT).show();}
else if (hours2< missoins_time_calc){
Toast.makeText(select.this,"يوجد "+ (-hours2+missoins_time_calc)+" دقيقة زيادة على الوقت المخصص", Toast.LENGTH_SHORT).show();
}
/* ArrayList<missions> missionsList = dataAdapter.missionsList;
for(int i = 0; i< missionsList.size(); i++){
missions missions = missionsList.get(i);
if(missions.isSelected()){}}*/
}
});
}
}
I think the error is the way your arrayPeople List is being populated, if you say the sixth item gets you the first you can try reversing the order with
Collections.reverse(arrayPeople);
you can place this line of code below your holder.cbm.setOnClickListener on your adapter
Hope it helps.

Refresh ListView pressing option DialogFragment

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

android filter listview with edittext item come from database

i have a listview . in which item come from database listview has also checkbox . listview work fine . now i put a edittext on listview i wana filter my listview i try a lot . i do some thing like this.i use custom adapter.
this is my list data code
public class DataListActivity extends Activity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
FoodDbHelper foodDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
private Button button1;
ListDataAdapter dataAdapter = null;
Button button;
DataProvider dataProvider;
ArrayList<HashMap<String, String>> namessList;
EditText inputSearch;
String search_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.data_list_layout);
inputSearch = (EditText)findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changes the Text
listDataAdapter.getFilter().filter(cs);
}
#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
}
});
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(DataListActivity.this, button1);
//Inflating the Popup using xml file
popup.getMenuInflater()
.inflate(R.menu.popup_menu, popup.getMenu());
//registering popup with OnMenuItemClickListener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(DataListActivity.this);
a_builder.setMessage("Do You Want To Close This App !!!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), MainMenu.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("EXIT", true);
startActivity(intent);
//finish();
}
})
.setNegativeButton("No" , new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = a_builder.create();
alert.setTitle("Alert !!!");
alert.show();
// Toast.makeText(
// MainMenu.this,
// "You Clicked : " + item.getTitle(),
// Toast.LENGTH_SHORT
// ).show();
return true;
}
});
popup.show(); //showing popup menu
}
});
listView = (ListView) findViewById(R.id.list_View);
listDataAdapter = new ListDataAdapter(getApplicationContext(),
R.layout.row_layout) {
#Override
protected void showCheckedButton(int position, boolean value) {
// TODO Auto-generated method stub
final DataProvider item = (DataProvider) listDataAdapter
.getItem(position);
Log.i("", "");
item.setSelected(value);
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText
.append("The following dishes were selected...\n");
ArrayList<DataProvider> list = listDataAdapter
.getSelectedIndexes();
int sum = 0;
for (int i = 0; i < list.size(); i++) {
DataProvider dataProvider = list.get(i);
sum = sum + dataProvider.getCalorie();
responseText.append("\n" + dataProvider.getName()
+ " : " + dataProvider.getCalorie()
+ " kcal"
);
}
Toast.makeText(getApplicationContext(), ""+responseText+"\n"+"................................."
+"\n"+"Total Calories In Your Menu Is : " +sum,
Toast.LENGTH_LONG).show();
}
});
}
};
listView.setAdapter(listDataAdapter);
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getReadableDatabase();
cursor = foodDbHelper.getInformations(sqLiteDatabase);
if (cursor.moveToFirst()) {
do {
String name, quantity, fat, protein, sugar, carbohydrates;
boolean selected = false;
String names = null;
Integer calorie;
name = cursor.getString(0);
quantity = cursor.getString(1);
calorie = Integer.valueOf(cursor.getString(2));
fat = cursor.getString(3);
protein = cursor.getString(4);
sugar = cursor.getString(5);
carbohydrates = cursor.getString(6);
DataProvider dataProvider = new DataProvider(name, quantity,
calorie, fat, protein, sugar, carbohydrates, names, selected);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getApplicationContext(),
"dish name is : " + name, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),
Detail.class);
}
});
}
public void gobackk(View view) {
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
}
}
this is custom adapter code
public abstract class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
boolean index[];
public ListDataAdapter(Context context, int resource) {
super(context, resource);
index = new boolean[list.size()];
}
static class LayoutHandler {
TextView name, quantity, calorie, fat, protein, sugar, carbohydrates;
CheckBox names;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
index = new boolean[list.size()];
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout, parent, false);
layoutHandler = new LayoutHandler();
layoutHandler.name = (TextView) row
.findViewById(R.id.text_dish_name);
layoutHandler.quantity = (TextView) row
.findViewById(R.id.text_dish_quantity);
layoutHandler.calorie = (TextView) row
.findViewById(R.id.text_dish_calorie);
layoutHandler.fat = (TextView) row.findViewById(R.id.text_dish_fat);
layoutHandler.protein = (TextView) row
.findViewById(R.id.text_dish_protein);
layoutHandler.sugar = (TextView) row
.findViewById(R.id.text_dish_sugar);
layoutHandler.carbohydrates = (TextView) row
.findViewById(R.id.text_dish_carbohydrates);
layoutHandler.names = (CheckBox) row.findViewById(R.id.checkBox1);
row.setTag(layoutHandler);
} else {
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.name.setText(dataProvider.getName());
layoutHandler.quantity.setText(dataProvider.getQuantity());
layoutHandler.calorie
.setText(String.valueOf(dataProvider.getCalorie()));
layoutHandler.fat.setText(dataProvider.getFat());
layoutHandler.protein.setText(dataProvider.getProtein());
layoutHandler.sugar.setText(dataProvider.getSugar());
layoutHandler.carbohydrates.setText(dataProvider.getCarbohydrates());
//layoutHandler.names.setChecked(dataProvider.isSelected());
layoutHandler.names.setTag(position);
layoutHandler.names.setChecked(index[position]);
layoutHandler.names
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
int pos = (Integer) buttonView.getTag();
index[pos] = isChecked;
showCheckedButton(position, isChecked);
}
});
return row;
}
public ArrayList<DataProvider> getSelectedIndexes() {
int size = list.size();
ArrayList<DataProvider> selectedItems = new ArrayList<DataProvider>();
for (int i = 0; i < size; i++) {
DataProvider cItem = (DataProvider) list.get(i);
if (index[i]) {
selectedItems.add(cItem);
}
}
return selectedItems;
}
protected abstract void showCheckedButton(int position, boolean value);
}

Android ListAdapter not refreshing immediately after delete

In my android application, I have a list in fragment using an adapter which extends ArrayAdapter. Whenever you hold a row item for long you can delete that row by clicking Yes on an alert-dialogue. But when you click Yes, last row seems to be deleted. When you close that fragment and come back on it then the view is fine with proper row deleted. After debugging for so many days I am unable to fix this.Can anyone please figure out whats wrong ?
Thanks in advance.
AdapterClass
public class DuasListAdapter extends ArrayAdapter<String> {
// class variables
private final Context context;// to save context
private final List<String> duas;// to save list of stores
LayoutInflater inflater;// so save layout inflater for the view
public DuasListAdapter(Context ctx, List<String> duasList) {
super(ctx, R.layout.adapter_list_duas, duasList);
context = ctx;// save context
duas = duasList;// save list of stores
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);// save inflater layout
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// if view is not loaded
if (!(convertView instanceof View)) {
convertView = inflater.inflate(R.layout.adapter_list_duas, parent, false);
// load the view from holder class
holder = new ViewHolder(convertView);
// set the tag for future use
convertView.setTag(holder);
}
// if view is loaded
else
// get view from tag
holder = (ViewHolder) convertView.getTag();
holder.duaIndex = position;
convertView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
final View view = v;
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
ViewHolder holder = (ViewHolder) view.getTag();
int index = holder.duaIndex;
((MainActivity) context).removeItemFromList(index);
Toast.makeText(view.getContext(), "Deleted", Toast.LENGTH_LONG).show();
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Delete Dua from Favorites?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
return false;
}
});
return convertView;
}
ListFragment
public void removeItemFromList(int index) {
String verses = new SharedPreferencesSupplication().read(SingletonClass.keyListOfVerses, "a1");
String[] versesList = verses.split(",");
String identifier = versesList[index];
new FavoriteDuas().removeDua(identifier);
updatedData();
}
#Override
public void onResume() {
lvDuaas.setAdapter(duasAdapter);
updatedData();
super.onResume();
}
#Override
public void onPause() {
// TODO Auto-generated method stub
lvDuaas.setAdapter(duasAdapter);
updatedData();
super.onPause();
}
public void updatedData() {
boolean keyIsFavSel = new SharedPreferencesSupplication().read(SingletonClass.keyIsFavSelected, false);
if (keyIsFavSel)
new SharedPreferencesSupplication().save(SingletonClass.keyListOfVerses, new SharedPreferencesSupplication().read(SingletonClass.keyFavVerses, "a1"));
String verses = new SharedPreferencesSupplication().read(SingletonClass.keyListOfVerses, "a1");
String[] versesList = verses.split(",");
ArrayList<String> duas = new ArrayList<String>();
for (int i = 0; i < versesList.length; i++) {
if (versesList[i].length() > 0)
duas.add(versesList[i]);
}
duasAdapter.clear();
if (duas.size() > 0) {
for (String object : duas) {
duasAdapter.insert(object, duasAdapter.getCount());
}
}
duasAdapter.notifyDataSetChanged();
}
Delete-Method
public void removeDua(String duaIdentifier) {
String verses = new SharedPreferencesSupplication().read(SingletonClass.keyFavVerses, "");
String[] versesList = verses.split(",");
int indexFound = -1;
for (int i = 0; i < versesList.length; i++) {
if (versesList[i].equals(duaIdentifier)) {
indexFound = i;
break;
}
}
if (indexFound >= 0) {
verses = "";
for (int i = 0; i < versesList.length; i++) {
if (indexFound != i) {
if (verses.isEmpty())
verses = versesList[i];
else
verses = verses + "," + versesList[i];
}
}
new SharedPreferencesSupplication().save(SingletonClass.keyFavVerses, verses);
}
}
You can try to re-instantiate the duasAdapter
duasAdapter = new DuasListAdapter(your_context_here, duas);
instead of
duasAdapter.clear();
if (duas.size() > 0) {
for (String object : duas) {
duasAdapter.insert(object, duasAdapter.getCount());
}
}
duasAdapter.notifyDataSetChanged();
You are using setOnLongClickListener() on your view, use setOnItemLongClickListener() instead.

Custom Listview using Base adapter not scrolls fast in Android

Hi I am working with android application which is having custom listview. The items in listview around 3000. My problem is after loading items when scrolling it makes outOfMemory Error.
I am using Base Adapter and Each item having One Checkbox and four textviews.
Here is my code. Please let me know the solution.
public class GuestListAdapter extends BaseAdapter implements OnClickListener {
private String strExe;
AlertDialog.Builder builder;
String sId;
String sCheckIn;
String strCheckInResponse;
Context context;
private ArrayList<String> arrayListId;
private ArrayList<String> arrayListFirstName;
private ArrayList<String> arrayListLastName;
private ArrayList<String> arrayListGuests;
private ArrayList<String> arrayCustomOne;
private ArrayList<String> arTempId;
public static ArrayList<Boolean> chickinlist;
public static ArrayList<Integer> arrCheckedItems;
public static ArrayList<Integer> arrUnCheckedItems;
Button btnInfo;
private SQLiteAdapter mySqliteAdapter;
private GuestListScreen myGuestList;
private RelativeLayout views;
private String strAlertValue;
// private AlertDialog alertDialog = null;
private ArrayList<Boolean> checks = new ArrayList<Boolean>();
public GuestListAdapter(Context mcontext, ArrayList<String> arrListid,
ArrayList<String> arrListFN, ArrayList<String> arrListLN,
ArrayList<String> arrListGuest, ArrayList<String> arrTiketID,
ArrayList<String> arrCustOne, ArrayList<Boolean> chicklist) {
clearAdapter();
arrayListId = new ArrayList<String>();
arrayListFirstName = new ArrayList<String>();
arrayListLastName = new ArrayList<String>();
arrayListGuests = new ArrayList<String>();
arrayCustomOne = new ArrayList<String>();
arTempId = new ArrayList<String>();
chickinlist = new ArrayList<Boolean>();
arrCheckedItems = new ArrayList<Integer>();
arrUnCheckedItems = new ArrayList<Integer>();
arrayListId = arrListid;
arrayListFirstName = arrListFN;
arrayListLastName = arrListLN;
arrayListGuests = arrListGuest;
arrayCustomOne = arrCustOne;
arTempId = arrTiketID;
chickinlist = chicklist;
context = mcontext;
mySqliteAdapter = new SQLiteAdapter(context);
for (int i = 0; i < arrayListFirstName.size(); i++) {
checks.add(i, false);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayListFirstName.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayListFirstName.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
final int pos = position;
views = null;
LayoutInflater layoutInflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
views = (RelativeLayout) layoutInflator.inflate(
R.layout.guest_list_item, null);
final CheckBox chk = (CheckBox) views.getChildAt(0);
// Log.d("", "CheckBox Pos "+position);
chk.setId(position);
TextView txtView = (TextView) views.getChildAt(1);
TextView txtView2 = (TextView) views.getChildAt(2);
TextView txtView3 = (TextView) views.getChildAt(3);
final TextView txtView4 = (TextView) views.getChildAt(4);
TextView txtView5 = (TextView) views.getChildAt(6);
txtView5.setId(position);
// Log.d("", "Button Pos "+position);
txtView4.setId(position);
txtView4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, InfoScreen.class);
intent.putExtra("IDVALUE", arTempId.get(txtView4.getId()));
intent.putExtra("IDVALUE", arrayListId.get(position));
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
}
});
for (int dd = 0; dd < arrayListFirstName.size(); dd++) {
if (position == dd) {
// Log.d("", "Passsing arr size " + chickinlist.size());
Boolean result = chickinlist.get(position);
// Log.d("", "After " + result);
if (result == true) {
chk.setChecked(true);
arrCheckedItems.add(position);
views.setBackgroundResource(R.drawable.list_item_checked);
} else {
chk.setChecked(false);
arrUnCheckedItems.add(position);
views.setBackgroundResource(R.drawable.list_item_unchecked);
}
txtView.setText(arrayListFirstName.get(position));
txtView2.setText(arrayListLastName.get(position));
txtView3.setText("(" + arrayListGuests.get(position) + ")");
if (arrayCustomOne.get(position).equalsIgnoreCase("0")
|| arrayCustomOne.get(position).equalsIgnoreCase(null)
|| arrayCustomOne.get(position).equalsIgnoreCase(
"(null)")) {
txtView5.setText("");
} else {
txtView5.setText(arrayCustomOne.get(position));
}
}
}
chk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mySqliteAdapter.openToWrite();
sId = arrayListId.get(chk.getId());
// Log.d("Adapter",
// "Checked Temp Id "+arTempId.get(chk.getId()));
if (isChecked) {
chk.setChecked(true);
arrCheckedItems.add(position);
strAlertValue = "1";
sCheckIn = "1";
strExe = "update ticket_details set checkin_status=1 where tempid="
+ arTempId.get(chk.getId());
mySqliteAdapter.executeCheckQurey(strExe);
if (Util.getInstance(context).isTabletDevice()) {
buttonView
.setBackgroundResource(R.drawable.tablet_list_item_check);
Log.e("Tablet", "Tablet Checked ");
} else {
buttonView
.setBackgroundResource(R.drawable.list_item_checked);
Log.e("Device", "Device Checked ");
}
new CheckInUpdate().execute();
AlertDialog.Builder builder = new AlertDialog.Builder(
context);
builder.create();
builder.setMessage(arrayListFirstName.get(chk.getId())
+ " " + arrayListLastName.get(chk.getId())
+ " has been checked in.");
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
Intent intentNavGuestList = new Intent(
context, GuestListScreen.class);
intentNavGuestList
.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intentNavGuestList);
dialog.dismiss();
}
}).show();
// Log.d("", "ID = " + buttonView.getId());
}
if (!isChecked) {
sCheckIn = "0";
strAlertValue = "0";
strExe = "update ticket_details set checkin_status=0 where tempid="
+ arTempId.get(chk.getId());
mySqliteAdapter.executeCheckQurey(strExe);
if (Util.getInstance(context).isTabletDevice()) {
buttonView
.setBackgroundResource(R.drawable.tablet_list_item_uncheck);
Log.e("Tablet", "Tablet UnChecked ");
} else {
buttonView
.setBackgroundResource(R.drawable.list_item_unchecked);
Log.e("Device", "Device UnChecked ");
}
new CheckInUpdate().execute();
Intent intentNavGuestList = new Intent(context,
GuestListScreen.class);
intentNavGuestList
.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intentNavGuestList);
}
}
});
return views;
}
#Override
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Integer index = (Integer) view.getTag();
boolean state = checks.get(index.intValue());
checks.set(index.intValue(), !state);
}
public void clearAdapter() {
if (arrayListFirstName != null) {
arrayListFirstName.clear();
arrayListId.clear();
arrayListId = null;
arrayListFirstName = null;
arrayListLastName.clear();
arrayListLastName = null;
arrayListGuests.clear();
arrayListGuests = null;
arrayCustomOne.clear();
arrayCustomOne = null;
arTempId.clear();
arTempId = null;
chickinlist.clear();
chickinlist = null;
arrCheckedItems.clear();
arrCheckedItems = null;
arrUnCheckedItems.clear();
arrUnCheckedItems = null;
}
}
}
I also tried with View Holder but still loading slow. Please tell the solution how to solve this.
You need to reuse view paremeter from View getView(final int position, Vie view, ViewGroup parent) and if it's not null, then You don't need to inflate again.
Use ViewHolder pattern;
remove loop for (int dd = 0; dd < arrayListFirstName.size(); dd++) from getView;
Try simplify layout for list items;
Seems arrayListFirstName.size() can be simplified (e.g. use some variable to avoid size() calls)
Do profiling in order to know exactly what is slow downs You scrolling (It might be enough to profike only getView())
Also, check out this video from Google I/O for more details on how to make ListViews in a right way.

Categories

Resources