i have created a list view in my android project and its showing an empty list at the beginning of the ListView. All the data is showing accurately from the database. but it creates a null list at the top of the List view. for example if we are taking one record from the database, two records are showing. first record is null as shown in the picture here
I dont know the fault is in the custom adapter or the listview. several days i have searched for an solution and could not find. Please assist me to complete the project. thanks.
below i will past my custom adapter code and the ListView
Custom Adapter
else {
LISTVIEW = (ListView) findViewById(R.id.listView1);
customAdapter = new CustomAdapter();
LISTVIEW.setAdapter(customAdapter);
LISTVIEW.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
LISTVIEW.setStackFromBottom(true);
}
static class ViewHolder {
TextView ord_num;
TextView cus_name;
TextView cus_tel;
TextView ord_status;
}
class CustomAdapter extends BaseAdapter {
#Override
public int getCount() {
return ID_ArrayList.size() + 1;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return -1;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder = null;
if (view == null) {
view = getLayoutInflater().inflate(R.layout.listtemplate, viewGroup,false);
holder = new ViewHolder();
holder.ord_num = (TextView) findViewById(R.id.lblID);
holder.cus_name = (TextView) findViewById(R.id.cus_name);
holder.cus_tel = (TextView) findViewById(R.id.cus_tel);
holder.ord_status = (TextView) findViewById(R.id.ord_status);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
try {
holder.ord_num.setText("Order ID :" + ID_ArrayList.get(i));
holder.cus_name.setText("Name : " + NAME_ArrayList.get(i));
holder.cus_tel.setText("Telephone No : " + PHONE_NUMBER_ArrayList.get(i));
holder.ord_status.setText("Status : " + STATUS_ArrayList.get(i));
} catch (Exception ex) {
System.out.println(ex);
}
final int a=i;
view.findViewById(R.id.item_info).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, View_Items.class);
String x = getItem(a).toString();
String y = ID_ArrayList.get(Integer.parseInt(x)-1).toString();
AlertDialog.Builder alt = new AlertDialog.Builder(MainActivity.this)
.setTitle("HI")
.setMessage(y);
alt.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alt.show();
}
});
return (view != null) ? view : null;
Here is My ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.a_hamoud.listview_sqlserver.MainActivity"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main">
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="8"
>
</ListView>
Please help me to find where the error is.
Thanks.
Try change:
holder.ord_num = (TextView) findViewById(R.id.lblID);
holder.cus_name = (TextView) findViewById(R.id.cus_name);
holder.cus_tel = (TextView) findViewById(R.id.cus_tel);
holder.ord_status = (TextView) findViewById(R.id.ord_status);
to:
holder.ord_num = (TextView) view.findViewById(R.id.lblID);
holder.cus_name = (TextView) view.findViewById(R.id.cus_name);
holder.cus_tel = (TextView) view.findViewById(R.id.cus_tel);
holder.ord_status = (TextView) view.findViewById(R.id.ord_status);
Also remove the +1 in getCount(). Hope that helps!
before set text you must check one codition which is null in your list at first index.
if (ID_ArrayList.get(i) != null){
holder.ord_num.setText("Order ID :" + ID_ArrayList.get(i));
holder.cus_name.setText("Name : " + NAME_ArrayList.get(i));
holder.cus_tel.setText("Telephone No : " + PHONE_NUMBER_ArrayList.get(i));
holder.ord_status.setText("Status : " + STATUS_ArrayList.get(i));
}
i dont know which field is null show you can check.
The adapter thinks it has more items than it really has. Remove the +1 in getCount():
#Override
public int getCount() {
return ID_ArrayList.size();
}
Just update your update your getCount method with this one
#Override
public int getCount() {
return ID_ArrayList.size();
}
Related
I have a method that add days in the date of the listview, the problem is when I scroll down and up again the values are changed, I have 2 kinds of date, so the method has to be called when the second kind appears in the list, but how can I use the method once so it doesn't keep adding each time I scroll it?
public class FaturasAdapter extends ArrayAdapter<Faturas> {
private Activity activity;
private LayoutInflater inflater;
private List<Faturas> faturasItens;
private Ferramentas mFerramentas;
private String entrada;
private String parcela = "";
private Map<Integer, Integer> intervaloMap;
private String data ="";
public FaturasAdapter(Activity activity, RealmList<Faturas> inItems) {
super(activity, R.layout.faturas_adapter, inItems);
this.activity = activity;
this.faturasItens = inItems;
this.mFerramentas = new Ferramentas();
this.intervaloMap = new HashMap<Integer, Integer>();
}
#Override
public int getCount() {
return faturasItens.size();
}
#Override
public Faturas getItem(int location) {
return faturasItens.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
final Faturas mFaturas = faturasItens.get(position);
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
vi = inflater.inflate(R.layout.faturas_adapter, null);
holder = new ViewHolder();
holder.numero = (TextView) vi.findViewById(R.id.numero);
holder.intervalo = (TextView) vi.findViewById(R.id.intervalo);
holder.valor = (TextView) vi.findViewById(R.id.valor);
holder.data = (TextView) vi.findViewById(R.id.data);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
addIntervalo(mFaturas.getIntervalo(), mFaturas.getTipo());
data = mFerramentas.dataText(intervaloMap.get(mFaturas.getTipo()));
holder.intervalo.setText(String.valueOf(mFaturas.getIntervalo()));
if (mFaturas.getTipo() == Faturas.intervaloConstanteEntrada) {
entrada = "ENT - ";
holder.numero.setText(entrada + mFaturas.getOrder() + "/" + mFaturas.getQtParcelasEntrada());
holder.valor.setText(String.valueOf(mFaturas.getValor()) + " ");
} else {
parcela = "PAR - ";
holder.numero.setText(parcela + mFaturas.getOrder() + "/" + mFaturas.getQtParcela());
holder.valor.setText(String.valueOf(mFaturas.getValor()) + " ");
}
holder.data.setText(data);
return vi;
}
private void addIntervalo(int intervalo, int tipo) {
int intervaloSum = intervalo;
if (!intervaloMap.isEmpty()) {
if (intervaloMap.get(tipo) != null)
intervaloSum += intervaloMap.get(tipo);
}
intervaloMap.put(tipo, intervaloSum);
}
public List<Faturas> getfaturasItens() {
return faturasItens;
}
public void setData(List<Faturas> fat) {
this.faturasItens.addAll(fat);
this.notifyDataSetChanged();
}
public class ViewHolder {
TextView numero;
TextView intervalo;
TextView data;
TextView valor;
}
}
As I said in my comment I don't see why do you need to call the addIntervalo() method in the getView() method. The problem with this is that getView() will be called a lot as the user uses the ListView so you'll end up adding the same data again and again.
From your code it seems you just show the data calculated with addIntervalo()(I'm assuming each item will present its data relative to the total that you calculate for that type that you calculate with addIntervalo()) so you could simply calculate in advance the values and then in getView() simply use that.
// in the constructor you get the data so calculate the values
// iterating over the data
public FaturasAdapter(Activity activity, RealmList<Faturas> inItems) {
super(activity, R.layout.faturas_adapter, inItems);
this.activity = activity;
this.faturasItens = inItems;
this.mFerramentas = new Ferramentas();
this.intervaloMap = new HashMap<Integer, Integer>();
foreach(Faturas f : inItems) {
addIntervalo(f.getIntervalo(), f.getTipo());
}
}
You also have the setData() method where you update the data list so you also need to calculate the result of addIntervalo() for the new items that are about to be added to the adapter:
public void setData(List<Faturas> fat) {
// because you're adding the fat list to the current set of items
// simply calculate addIntervalo() for them to add their count to the total
foreach(Faturas f : fat) {
addIntervalo(f.getIntervalo(), f.getTipo());
}
this.faturasItens.addAll(fat);
this.notifyDataSetChanged();
}
In getView() remove the line:
addIntervalo(mFaturas.getIntervalo(), mFaturas.getTipo());
as you already calculated the values.
Oh, it's problem for base android list's widget to change view. You should know, that ListView and RecycleView caching and invalidating views per scrolling! So your views will be changed to default type!
RecycleView has solution, it's using several type from method getItemType(). But you work with ListView. Anyway! Better solution it's use special list widget which supports custom views and changing that views in anytime. For this task use LinkedListView!
I'm facing a strange behaviour using an ArrayAdapter.
When the number of listview item exceed the height of the listView (say after item 8), the next item get the id 0 instead the id 9.
In my opinion this type of issue was explained here with the convertView, but i use it in the same way (i think).
The following code is my ArrayAdapter.
public class StepsAdapter extends ArrayAdapter<String> {
Context context;
List<String> steps;
public StepsAdapter(Context context, int resourceId, List<String> steps) {
super(context, resourceId, steps);
this.context = context;
}
private class ViewHolder {
EditText stepValue;
ImageView removeStep;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
final String step = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_step, null);
holder = new ViewHolder();
holder.stepValue = (EditText) convertView.findViewById(R.id.stepEdit);
holder.removeStep = (ImageView) convertView.findViewById(R.id.removeStep);
holder.stepValue.setText(step);
holder.removeStep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"* Remove id step " + position, Toast.LENGTH_LONG).show();
steps.remove(position);
notifyDataSetChanged();
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
}
Then my main activity where i get existing data and put it in my listView, the add button and the save button.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_game);
mContext = getApplicationContext();
steps = new ArrayList<String>();
stepsAdapter = new StepsAdapter(mContext,R.layout.row_step,steps);
Gson gson = new GsonBuilder().create();
game = gson.fromJson(gameJson, Games.class);
/*
* Settings values
*/
gameNameValue.setText(game.getName());
gameBackgroundPreview.setBackgroundColor(game.getColor());
colorSelected = game.getColor();
for(int i = 0; i < game.getSteps().size() ; i++){
//steps.add(game.getSteps().get(i).toString());
//notifyDataSetChanged();
stepsAdapter.add(game.getSteps().get(i).toString());
}
final ListView listSteps = (ListView) findViewById(R.id.listViewSteps);
listSteps.setAdapter(stepsAdapter);
gameNameValue.setText(gameName);
addSteps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stepsId = steps.size();
Toast.makeText(getApplicationContext(), "addSteps : " + stepsId, Toast.LENGTH_LONG).show();
stepsAdapter.insert("newstep", stepsId);
}
});
buttonSaveGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String valueEditGameName = gameNameValue.getText().toString();
int valueColorBackaground = colorSelected;
String picture = "testPic";
for(int i=0; i < listSteps.getChildCount(); i++) {
LinearLayout rowLayout = (LinearLayout) listSteps.getChildAt(i);
//Log.e(TAG, ">> :) layout >>" + listSteps.getChildAt(i).getClass().getName());
EditText editRow = (EditText) rowLayout.getChildAt(0);
stepsValues.add(editRow.getText().toString());
//Log.e(TAG, ">> :) inside layout >>" + editRow.getText().toString());
}
if(valueEditGameName.trim().length() > 0 && picture.trim().length() >0 ){
Games game = new Games(valueEditGameName,valueColorBackaground,picture,stepsValues);
String goToSave = game.createJson();
Log.e(TAG, ">>Saved>>" + goToSave);
final CkdFile file = new CkdFile();
String saved = file.writeToSDFile(game.getName(), goToSave);
Toast.makeText(mContext, saved, Toast.LENGTH_LONG).show();
Intent backToMain = new Intent(mContext,MainActivity.class);
startActivity(backToMain);
} else {
Toast.makeText(mContext, "Fill all texts", Toast.LENGTH_LONG).show();
}
}
});
}
I try to add items in 2 different ways :
add item through : List steps
add item through : StepsAdapter stepsAdapter
Both give me same behaviour.
If someone has a clue to help understanding what i'm doing wrong with my implementation of ListView/ArrayAdapter.
Thanks in advance !
EDIT 1 :
After pushing some logs everywere, it understand the strange behaviour :
My adapter have only 6 slots (the limit came from the size of the listview in layout), and when my arraylist have more than 6 items, the getView select items only between 0 and 5.
I'm searching now a way to get the position in ArrayList and not the position in arrayadapter.
I faced same issue recently. Add following overrides to Adapter:
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
I found a simple xml "trick" to avoid this behaviour : i set a biger height to listView.
<ListView
android:layout_width="match_parent"
android:layout_height="1000dp"
android:layout_gravity="center_horizontal"
android:id="#+id/listViewSteps"
android:layout_margin="10dp">
</ListView>
It's not really resolve but a take it ...
I have a listview to populate data with a CustomAdapter as shown below by code.
1.) The listview rows are clickable and onItemClick I show up two buttons retake/review.
2.) When I click on other row the buttons which were visible on the previous row should hide.
3.) When I scroll the list all buttons are again invisible , that should not happen.
I have achieved the point no. 1 by this code , but how could I achieve 2,3. How could I modify getView() method of adapter or onItemClick() so that things work proper.
//Initialized listview with adapter
AttempListView.setAdapter(new AttemptedExcerciseAdapter(mAttempRecord,AttemptedExercise.this));
//A different adapter class to place values
public class AttemptedExcerciseAdapter extends BaseAdapter{
HashMap<Integer, AttemptedRecord> mHashMap;
Context mContext;
LinearLayout mLLButton;
public AttemptedExcerciseAdapter() {
// TODO Auto-generated constructor stub
}
public AttemptedExcerciseAdapter(HashMap<Integer, AttemptedRecord> mAttempRecord,Context mContext) {
this.mHashMap = mAttempRecord;
this.mContext=mContext;
}
#Override
public int getCount() {
return mHashMap.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
if (convertView == null) {
#SuppressWarnings("static-access")
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(AttemptedExercise.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.exerciselistlayout, null);
}
TextView attempChapter_name = (TextView) convertView.findViewById(R.id.TVchapterexercisechapterName);
TextView attemptQues = (TextView) convertView.findViewById(R.id.tvexercisesuccessrate);
TextView attemptSR = (TextView) convertView.findViewById(R.id.tvexerciseperquestiontime);
Button ReviewButton = (Button) convertView.findViewById(R.id.ReviewButton);
Button RetakeButton = (Button) convertView.findViewById(R.id.RetakeButton);
LinearLayout mLLtext = (LinearLayout) convertView.findViewById(R.id.LLText);
mLLButton = (LinearLayout) convertView.findViewById(R.id.LLButton);
mLLButton.setVisibility(View.INVISIBLE);
mLLtext.setVisibility(View.VISIBLE);
System.out.println("data value is..."+position+mHashMap.get(position + 1).getChapter_name());
attempChapter_name.setText(mHashMap.get(position+1).getChapter_name());
attemptQues.setText(" " + mHashMap.get(position+1).getTimePerQues() + " sec/ques");
attemptSR.setText(" " + mHashMap.get(position+1).getSuccess_rate() + " %");
return convertView;
}
}
//Item click listener for listview
public class ExcerciseItemClickListener implements OnItemClickListener {
ArrayList<Integer> rowNo=new ArrayList<Integer>();
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
System.out.println("click working..."+arg2);
arg1.findViewById(R.id.LLButton).setVisibility(View.INVISIBLE);
rowNo.clear();
rowNo.add(arg2);
if(rowNo.size()==1)
{
AttemptedRecord mRecordExcerciseItem = mAttempRecord.get(arg2 + 1);
final int chapter_id = mRecordExcerciseItem.getChapter_id();
final int test_id = mRecordExcerciseItem.getTest_id();
final int subject_id = mRecordExcerciseItem.getSubject_id();
System.out.println("attempted list size is..."+mAttempRecord.size());
arg1.findViewById(R.id.LLText).setVisibility(View.INVISIBLE);
arg1.findViewById(R.id.LLTake).setVisibility(View.INVISIBLE);
arg1.findViewById(R.id.LLButton).setVisibility(View.VISIBLE);
Button review=(Button) arg1.findViewById(R.id.ReviewButton);
Button retake=(Button) arg1.findViewById(R.id.RetakeButton);
review.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBHelper mDbHelper = new DBHelper(AttemptedExercise.this);
mDbHelper.createOrOpenDatabase("Dashboard");
Cursor chpater_exercise_Cursor = mDbHelper.rawQuery("select current_test_id from practice_test_summary where test_id="+test_id+" order by test_datetime desc limit 1");
chpater_exercise_Cursor.moveToFirst();
Long current_test_id =chpater_exercise_Cursor.getLong(0);
chpater_exercise_Cursor.close();
System.out.println("value of current test id is...."+current_test_id);
Intent reviewIntent = new Intent(AttemptedExercise.this, PracticeReview.class);
reviewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
if (current_test_id > 0) {
reviewIntent.putExtra("current_test_id", current_test_id);
startActivity(reviewIntent);
}
}
});
retake.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("test id value when test starts is... "+test_id);
Toast.makeText(AttemptedExercise.this, "chapter_id" + chapter_id + " course_id" + " test_id" + test_id + " subject_id" + subject_id, Toast.LENGTH_LONG).show();
StartTest(4, subject_id, chapter_id, test_id);
}
});
}
}
}
In getView, you hide the button and text,that's why the view dispears when you scrolling。
mLLButton.setVisibility(View.INVISIBLE);
mLLtext.setVisibility(View.VISIBLE);
In your click listener you should record the position of the selected row, and in getView, you need to set view's visilibity status based on the postion of the view.
if you can mange to add ClickListeners of the list in getView like this
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
curruntButtonClickPosition=position;
//Visible you button here
notifyDataSetChanged();
}
});
and in getView
if(curruntButtonClickPosition=position)
//mLLButton visible
else
//mLLButton invisible
add curruntButtonClickPosition globle variable in AttemptedExcerciseAdapter class and init with -1.
Below you can see the code, i implemented a simple adapter for my listview. But i can not get in to onListItemClick. can anyone has suggestions ?
actually it displays the list normally but i am not able to get onitemclick events . thanks in advance.
public class MyListActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<Frame> results = WebOperations
.loadList_Frame();
myAdapter = new MyListAdapter(MyListActivity.this);
myAdapter.internalList = results;
setListAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
};
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " please show toast!!!!!!!!!", Toast.LENGTH_LONG).show();
}
public static class MyListAdapter extends BaseAdapter {
public ArrayList<Frame> internalList;
public LayoutInflater mInflater;
public int pageCount = 0;
public MyListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
if (internalList == null)
return 0;
return internalList.size();
}
public Object getItem(int position) {
if (internalList == null || internalList.size() < position)
return null;
return internalList.get(position);
}
public long getItemId(int position) {
if (internalList == null || internalList.size() < position)
return 0;
return internalList.get(position).getId();
}
public View getView(int position, View arg1, ViewGroup parent) {
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.entryrow, null);
try {
String gunlukText = String.format(" %s ",
internalList.get(position).getKeyText().toString());
TextView entry = (TextView) v
.findViewById(R.id.textViewEntryText);
entry.setText((CharSequence) gunlukText);
} catch (Exception e) {
Log.d("aaaaaaaaaaaaaaaaaaa", "errorrrrrrrrrrr");
}
}
return v;
}
}
}
EDIT 1 : I am adding entry_row layout xml file below.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewEntryText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:padding="5dp"
android:paddingLeft="10dp"
android:text="#string/Ana_Sayfa"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
You should consider adding your listener to your listview :
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " please show toast!!!!!!!!!", Toast.LENGTH_LONG).show();
}
});
add onclicklistener into getView method just before return view.
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.w("position", position + "");
}
});
check if it helps..
Didi you try, on your layout/entryrow, to add the addStatesFromChildrenattribute and set it to true ?
http://developer.android.com/reference/android/view/ViewGroup.html#attr_android:addStatesFromChildren
Please refer one of the good example given in API demo of custom BaseAdapter from http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List13.html Just override onListItemCLicked and check. It works perfectly fine. Try to modify your code accordingly.
I have an activity which extends ListActivity. It has many things but amongst them it shows the articles the user has purchased with an adapter. Well I have a method that the user can delete the items from the list. The problem is when there is only one item. If I try to delete the last one the app crashes. Here is a it of my code:
public class Ventas extends ListActivity {
......
lv = getListView();
......
protected void confirmRemoval(final int arg2) {
// TODO Auto-generated method stub
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(getResources().getString(R.string.ventas));
alertDialog.setMessage(getResources().getString(R.string.confirmacion2));
alertDialog.setButton("Si",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if(adapter2.mEvents.size()>=1){
adapter2.mEvents.remove(arg2);
} else {
//doesn't work
/*adapter2=null;
adapter2.notifyDataSetInvalidated();
lv.setVisibility(View.GONE);*/
}
}
});
alertDialog.setButton2("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alertDialog.show();
}
here is the adapter and wrapper:
private class EventAdapter2 extends BaseAdapter {
public ArrayList<Articulo> mEvents = null;
public EventAdapter2(Context c, ArrayList<Articulo> clientes) {
mContext = c;
mEvents = clientes;
}
public int getCount() {
return mEvents.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
EventEntryView2 btv;
if (convertView == null) {
btv = new EventEntryView2(mContext, mEvents.get(position));
} else {
btv = (EventEntryView2) convertView;
String title1 = mEvents.get(position).getCantidad() + "";
if (title1 != null) {
btv.setText1Title(title1);
}
String title2 = mEvents.get(position).getDescripcion();
if (title2 != null) {
btv.setText2Title(title2);
}
String title3 = mEvents.get(position).getpVenta() + "0";
if (title3 != null) {
btv.setText3Title(title3);
}
String title4 = (mEvents.get(position).getCantidad() * mEvents
.get(position).getpVenta()) + "0";
if (title4 != null) {
btv.setText4Title(title4);
}
}
return btv;
}
private Context mContext;
}
private class EventEntryView2 extends LinearLayout {
private TextView text1;
private TextView text2;
private TextView text3;
private TextView text4;
private View inflatedView;
public EventEntryView2(Context context, Articulo resp) {
super(context);
this.setOrientation(VERTICAL);
inflatedView = View.inflate(context, R.layout.results, null);
text1 = (TextView) inflatedView.findViewById(R.id.textView1);
text2 = (TextView) inflatedView.findViewById(R.id.textView2);
text3 = (TextView) inflatedView.findViewById(R.id.textView3);
text4 = (TextView) inflatedView.findViewById(R.id.textView4);
String t = resp.getCantidad() + "";
text1.setText(t);
String t1 = resp.getDescripcion();
text2.setText(t1);
String t2 = resp.getpVenta() + "0";
text3.setText(t2);
String t3 = (resp.getCantidad() * resp.getpVenta()) + "0";
text4.setText(t3);
addView(inflatedView, new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
public void setText4Title(String title4) {
text4.setText(title4);
}
public void setText3Title(String title3) {
text3.setText(title3);
}
public void setText2Title(String title2) {
text2.setText(title2);
}
public void setText1Title(String title1) {
text1.setText(title1);
}
}
as you can see when I have only one item left I have tried to set adapter to null or adapter.notifyDataSetInvaliadted or even making the listview invisible, nothing works. What happens is when I click ok nothing changes then when I click a second time it all crashes
What I would like is the listView to disappear when the adapter is empty but I am now out of ideas, is it even possible?
Any ideas?
EDIT:
Thank you all for the answers but the problem was I was modifying the list from inside an inner anonymous class. It is actually pretty simple, create a method and call it from inside the dialog, once the array is empty the list disappears automatically:
protected void removeFromList(int arg2) {
adapter2.mEvents.remove(arg2);
adapter2.notifyDataSetChanged();
}
remove item from the arraylist which you add into the adapter and then call this method.
youradapter.notifyDataSetChanged();
and whatever you do for single item that was
adapter2 = null;
adapter2.notifyDataSetInavlidated();
this will obviously crash it because adapter2 object was null so how null object notify its data
Try calling lv.invalidate() after the remove() and see whether that makes any difference.
You should check in your adapter class if it is null then you should not fetch value from it......that's the main reason why you are getting exception as you are fetching the value from null variable.Put check there.
For setVisibility to Work:
You create your main.xml
Add to it a ListView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/sherif.android.deedz"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/myListView"
android:divider="#ffa500" android:dividerHeight="1px"
android:background="#drawable/somedrawable_xml"
android:choiceMode="singleChoice"></ListView>
</ListView>
Now you can make it GONE
If you want the whole details of this :
Check my answer