简体   繁体   中英

Android - Display Alert Dialog for empty ListView

How to show the alert dialog for the empty list view when there are no listview items. Please find the below image having three text fields. I have to implement the empty list view when there are no records/unmatched records in the list.

The list view is implemented as below:

ListView empListView; 
empListView = (ListView)findViewById(R.id.list1 );

I have to show the alert dialog box for the empListView. Please help me with the samplecode/links.

As per my opinion, No need to check the size of arraylist or adapter item count.

Instead of displaying alert dialog, you can just display message "Sorry no records found" message on the listview. for the same you have to set the empty view by using setEmptyView() method of ListView.

For example:

listViewFriends.setEmptyView(findViewById(R.id.empty));

I think you are paasing arraylist or some other data in setadapter method And if you are using arraylist then you have to check that size of arraylist before calling the setadapter method.

if(a.size()>0)
    {
    lv = (ListView) findViewById(R.id.frendlist);
    lv.setAdapter(new ListAdapter(this, R.id.frendlist, a));
    }
    else
    {
        builder.setMessage(" You Have no friends") 
        .setCancelable(false)   
        .setPositiveButton("Ok", new DialogInterface.OnClickListener() 
        {      
            public void onClick(DialogInterface dialog, int id)
            {

            }   
            }) ; 

        AlertDialog alert = builder.create();
        alert.show();
    }

我认为您在setadapter方法中停顿arraylist或其他数据。如果您使用arraylist,则必须在调用setadapter方法之前检查arraylist的大小。

if(cdata.getCount()>0)
{
    CursorAdapter adapter = new MyCursorAdapter( getApplicationContext(), R.layout.listview, cdata, fields, names);
    listview.setAdapter(adapter);
}
else
{
    //create dialog here
}

It all depends on how you implement the setAdapter method etc. But here is an example:

if(cdata.getCount()==0) {
  //empty, show alertDialog
  AlertDialog.Builder builder = new AlertDialog.Builder(this);
  builder.setMessage("Search is empty")
   .setCancelable(true)
   .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
       }
   });
  AlertDialog alert = builder.create();
} 
else {
  //Not empty, set the adapter or do what you want. 
  empListview.setAdapter(new MyCursorAdapter( getApplicationContext(), R.layout.listview, cdata, fields, names));
}

The code above havent been tested. But should work with minor adjustments, I might have forgotten something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM