当列表视图中没有数据时显示对话框消息

时间:2013-12-10 11:50:21

标签: android list view dialog

我正在开发一个应用程序来显示我从Web服务收到的一些数据。我使用自定义适配器类作为从BaseAdapter类扩展的列表视图。我想在列表视图中没有数据时显示一个对话框。我尝试了getCount方法的帮助,该方法在我的适配器类中,但它没有用。有人可以告诉我该怎么做吗?

这是我的适配器类

public class NewsRowAdapter extends BaseAdapter  {

static Dialog dialogs;
private static final String STIME = "StartTime";
private static final String END = "EndTime";
private static final String DATE = "Date";
private Context mContext;
private Activity activity;
private static LayoutInflater inflater=null;
private ArrayList<HashMap<String, String>> data;
int resource;
    //String response;
    //Context context;
    //Initialize adapter
    public NewsRowAdapter(Context ctx,Activity act, int resource,ArrayList<HashMap<String, String>> d) {
        super();
        this.resource=resource;
        this.data = d;
        this.activity = act;
        this.mContext = ctx;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    public void showFirstDialog(final ArrayList<HashMap<String, String>> list){

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
        alertDialogBuilder.setTitle("Confirm your Action!");

        // set dialog message
        alertDialogBuilder
            .setMessage("You Have Similar Kind of Appoinments!! Do you wanna Show them ?")
            .setCancelable(false)
            .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {

                    Toast.makeText(mContext, "Showing", Toast.LENGTH_LONG).show();
                    dialogpop(list);


                }
              })
              .setNegativeButton("No",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });
        alertDialogBuilder.show();

    }

    public void dialogshow(final String Date,final String Start,final String End){

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
        alertDialogBuilder.setTitle("Confirm your Action!");

        // set dialog message
        alertDialogBuilder
            .setMessage("Click yes Confirm!!")
            .setCancelable(false)
            .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, close
                    // current activity
                    //MainActivity.this.finish();

                    Toast.makeText(mContext, "Yes clicked", Toast.LENGTH_LONG).show();

                    //check similer records






                    //if duplicates > 1 then show the popup list
                    //if(duplicateList.size()>1){

                        /*final Dialog dialogs = new Dialog(activity);
                        dialogs.setContentView(R.layout.dialog_list);
                        dialogs.setTitle("Select One");

                        ListView listView = (ListView) dialogs.findViewById(R.id.dialogList);
                        NewsRowAdapter nw = new NewsRowAdapter(mContext, activity, R.layout.dialog_row, duplicateList);
                        listView.setAdapter(nw);

                        listView.setOnItemClickListener(new OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> arg0,
                                    View arg1, int arg2, long arg3) {
                                // TODO Auto-generated method stub
                                dialogs.dismiss();
                            }
                        });
                        dialogs.show();*/




                //  }





                }
              })
              .setNegativeButton("No",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });
        alertDialogBuilder.show();

    }





    public void showDuplicateDialog(ArrayList<HashMap<String, String>> list){

        //CharSequence[] cs = list.toArray(new CharSequence[list.size()]);


        AlertDialog.Builder alertDialogBuilder2 = new AlertDialog.Builder(activity);
        LayoutInflater infl = activity.getLayoutInflater();
        View view = infl.inflate(R.layout.dialog_list, null);

        ListView lv = (ListView) view.findViewById(R.id.dialogList);

        //NewsRowAdapter nw = new NewsRowAdapter(mContext, activity, R.layout.dialog_row, list);

        SimpleAdapter sim = new SimpleAdapter(mContext, list, R.layout.dialog_row,  new String[] { STIME,END, DATE }, new int[] {
                R.id.stime2,R.id.etime2, R.id.blank2});
        lv.setAdapter(sim);
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                // TODO Auto-generated method stub
                Toast.makeText(mContext, "item clicked ", Toast.LENGTH_LONG).show();
            }
        });



        /*ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                  android.R.layout.two_line_list_item, android.R.id.text1, Names);*/

        alertDialogBuilder2.setView(view)
        /*alertDialogBuilder2.setAdapter(sim, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Toast.makeText(mContext, "item clicked ", Toast.LENGTH_LONG).show();
            }
        })
        */


        .setPositiveButton("Accept", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        Toast.makeText(mContext, "Accepted", Toast.LENGTH_LONG).show();
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                    }
                });

        alertDialogBuilder2.show();
    }



@Override
public View getView(final int position, View convertView, final ViewGroup parent) {


    View vi = convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.row,null);


        final TextView firstname = (TextView) vi.findViewById(R.id.fname);
        final TextView lastname = (TextView) vi.findViewById(R.id.lname);
        final TextView startTime = (TextView) vi.findViewById(R.id.stime);
        final TextView endTime = (TextView) vi.findViewById(R.id.etime);
        final TextView date = (TextView) vi.findViewById(R.id.blank);
        final TextView hidID = (TextView) vi.findViewById(R.id.hidenID);
        final ImageView img = (ImageView) vi.findViewById(R.id.list_image);


        HashMap<String, String> song = new HashMap<String, String>();
        song =data.get(position);

        firstname.setText(song.get(MainActivity.TAG_PROP_FNAME));
        lastname.setText(song.get(MainActivity.TAG_PROP_LNAME));
        startTime.setText(song.get(MainActivity.TAG_STIME));
        endTime.setText(song.get(MainActivity.TAG_ETIME));
        date.setText(song.get(MainActivity.TAG_DATE));
        hidID.setText(song.get(MainActivity.TAG_HID));

        //imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), img);

        Button accept = (Button) vi.findViewById(R.id.btnAccepted);
        accept.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                final int x = (int) getItemId(position);
                /*Intent zoom=new Intent(mContext, Profile.class);
                zoom.setFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
                zoom.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(zoom);*/

                // get the intent from the hashmap check if there is similar date and time.
                //then store them in a list or array.

                String getDate = (String) date.getText();
                String getStartTime = startTime.getText().toString();
                String getEndTime = endTime.getText().toString();


                ShortList sh = new ShortList();

                ArrayList<HashMap<String, String>> duplicateList; 
                duplicateList=sh.getDuplicated(getDate, getStartTime, getEndTime);

                if(duplicateList.size()>1){
                    //dialogshow(getDate,getStartTime,getEndTime);
                    showFirstDialog(duplicateList);
                }
                else{
                    dialogshow(getDate, getStartTime, getEndTime);

                }




            }
    });


        vi.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                String getPname = hidID.getText().toString();

                Toast.makeText(parent.getContext(), "view clicked: "+getPname , Toast.LENGTH_SHORT).show();

                //get the id of the view
                //check the id of the request
                //call the web service acording to the id





                Intent zoom=new Intent(parent.getContext(), Profile.class);  
                zoom.putExtra("PatientID", getPname);
                parent.getContext().startActivity(zoom);



            }
        });

        return vi;


}

public void dialogpop(ArrayList<HashMap<String, String>> list){

    dialogs = new Dialog(activity);
    dialogs.setContentView(R.layout.dialog_list);
    dialogs.setTitle("Select One");



    ListView listView = (ListView) dialogs.findViewById(R.id.dialogList);

    //SimpleAdapter sim = new SimpleAdapter(mContext, list, R.layout.dialog_row,  new String[] { STIME,END, DATE }, new int[] {
    //        R.id.stime2,R.id.etime2, R.id.blank2});

    Adapter_For_Dialog nw = new Adapter_For_Dialog(mContext,activity, R.layout.dialog_row, list);
    listView.setAdapter(nw);



    dialogs.show();

}





@Override
public int getCount() {
    // TODO Auto-generated method stub

        return data.size();

}



@Override
public Object getItem(int possision) {
    // TODO Auto-generated method stub
    return possision;
}



@Override
public long getItemId(int possision) {
    // TODO Auto-generated method stub
    return possision;
}
}

在我的主要活动中,我检查响应是否为空

这是我的主要活动

公共类MainActivity扩展了Activity {

EditText userName;
EditText passWord;
ListView list;
TextView fname;
TextView lname;
TextView stime;
TextView etime;
TextView date;
ImageButton login;

public static ArrayList<HashMap<String, String>> oslist;  

//URL to get JSON Array
//private static String url = "http://api.learn2crack.com/android/jsonos/";
private static String url ="my url is here";


public static  String confirm;
String firstName;

//JSON Node Names
 /*static final String TAG_OS = "android";
 static final String TAG_VER = "ver";
 static final String TAG_NAME = "name";
 static final String TAG_API = "api";*/


static final String TAG_DATA = "d";
static final String TAG_OBJ_1 = "Appointment";
static final String TAG_OBJ_2 = "PatientProfile";
static final String TAG_PROP_FNAME = "FirstName";
static final String TAG_PROP_LNAME = "LastName";
static final String TAG_STIME = "StartTime";
static final String TAG_ETIME = "EndTime";
static final String TAG_DATE = "Date";
static final String TAG_HID = "PatientPersonId";



//static final String TAG_API = "NickName";
JSONArray androids = null;
JSONObject duplicate;

public static JSONArray dupArray;

public JSONArray getJsonArray() {
    return dupArray;
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.loging);

    if (android.os.Build.VERSION.SDK_INT > 9)

    {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy); 

    }



    oslist = new ArrayList<HashMap<String, String>>();
    login = (ImageButton)findViewById(R.id.imageButton1);
    new ArrayList<HashMap<String, String>>();







    login.setOnClickListener(new OnClickListener() {

        @Override
        public
        void onClick(View v) {
            // TODO Auto-generated method stub

            //if login success then call below 
            userName = (EditText) findViewById(R.id.editUserName);
            passWord = (EditText) findViewById(R.id.editPassWord);

            String name = userName.getText().toString().trim();
            String passwd = passWord.getText().toString().trim();

            CheckLogin check = new CheckLogin();
            confirm = check.AuthenticateUser(name, passwd);



            if(!(confirm.equals("-1"))){
                new JSONParse().execute();
            }

            else{

                Toast.makeText(getBaseContext(), "Check Username or Password", Toast.LENGTH_LONG).show();
            }


        }
    });



}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    finish();
}





public class JSONParse extends AsyncTask<String, String, JSONObject> {
    private ProgressDialog pDialog;
   @Override
   protected void onPreExecute() {
       super.onPreExecute();
       fname = (TextView)findViewById(R.id.fname);
       lname = (TextView)findViewById(R.id.lname);
       stime = (TextView)findViewById(R.id.stime);
       etime = (TextView)findViewById(R.id.etime);
       date = (TextView)findViewById(R.id.blank);
       pDialog = new ProgressDialog(MainActivity.this);
       pDialog.setMessage("Getting Data ...");
       pDialog.setIndeterminate(false);
       pDialog.setCancelable(true);
       pDialog.show();

   }


   @Override
    protected JSONObject doInBackground(String... arg0) {
    // TODO Auto-generated method stub
       JsonParser jParser = new JsonParser();

       // Getting JSON from URL
       JSONObject json = null;
    try {

        JSONObject parm = new JSONObject();
        //parm.put("PersonID", confirm);
        parm.put("caregiverPersonId", confirm);
        json = jParser.getJSONFromUrl(parm,url);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        //Toast.makeText(getApplicationContext(), "Hi "+firstName+"You Don't Have Any Requests!", Toast.LENGTH_LONG).show();
    }
       return json;
}


   @Override
protected void onPostExecute(JSONObject json) {
    // TODO Auto-generated method stub
       pDialog.dismiss();
       try {
              // Getting JSON Array from URL
           //JSONObject jobs  = json.getJSONObject(TAG_DATA);

           String emptyjson = json.getString(TAG_DATA);

           if(emptyjson.equals("[]")){



               startActivity(new Intent(MainActivity.this,Empty.class));
           }
           else
           {

           androids = json.getJSONArray(TAG_DATA);


            //JSONObject appt= new JSONObject(json.getString("d"));


           for(int i = 0; i < androids.length(); i++){
              JSONObject c = androids.getJSONObject(i);

              // Storing  JSON item in a Variable

              JSONObject job  = c.getJSONObject(TAG_OBJ_2);

              firstName = job.getString(TAG_PROP_FNAME);
              String lastName = job.getString(TAG_PROP_LNAME);

              JSONObject job_two  = c.getJSONObject(TAG_OBJ_1).getJSONObject("DayTimeSlot");

              String start = job_two.getString(TAG_STIME );
              String end = job_two.getString(TAG_ETIME);


            /*  String ackwardDate = job_two.getString(TAG_DATE);;
              Calendar calendar = Calendar.getInstance();
              String ackwardRipOff = ackwardDate.replace("/Date(", "").replace(")/", "");
              Long timeInMillis = Long.valueOf(ackwardRipOff);
              calendar.setTimeInMillis(timeInMillis);
              String theDate = (calendar.getTime().toGMTString());
              */
              String Ldate = job_two.getString(TAG_DATE);
              String ackwardRipOff = Ldate.replace("/Date(", "").replace(")/", "");
              Long Ldat = Long.valueOf(ackwardRipOff);
              Date date = new Date(Ldat);
              String strdate = (String) DateFormat.format("MM/dd/yy", date);


              JSONObject toHid = c.getJSONObject(TAG_OBJ_1);

              String Hid = toHid.getString(TAG_HID);

              //String date = dateConvert(Ldate);
              //long Ldate = job_two.getLong("Date");


              //String strdate = (String) DateFormat.format("MM/dd/yy h:mmaa", date);

              // Adding value HashMap key => value

              HashMap<String, String> map = new HashMap<String, String>();

              map.put(TAG_PROP_FNAME, firstName);
              map.put(TAG_PROP_LNAME, lastName);
              map.put(TAG_STIME , start);
              map.put(TAG_ETIME, end);
              map.put(TAG_DATE, strdate);
              map.put(TAG_HID, Hid);

              oslist.add(map);

              //duplicate = new JSONObject();

              Intent reult = new Intent(MainActivity.this,ViewList.class);
              //reult.putStringArrayListExtra("map", oslist);
              //startActivity(reult);


              reult.putExtra("arraylist", oslist);
              startActivityForResult(reult, 500);



              }


           dupArray = new JSONArray();
           dupArray.put(oslist);
           }



            } catch (JSONException e) {
                e.printStackTrace();
          //Intent reult = new Intent(MainActivity.this,ViewList.class);
          //reult.putStringArrayListExtra("map", oslist);
         // startActivity(reult);



      }


   }
}


    public String dateConvert(String d){

        Date dt = new Date();
        SimpleDateFormat df= new SimpleDateFormat("dd/MM/yyyy");
        String strDate = df.format(dt);


        return strDate;


    }


}

这里是我的View List类,它是数据存在时的活动

public class ViewList extends Activity {

    private static final String TAG_VER = "ver";
    private static final String TAG_NAME = "name";
    private static final String TAG_API = "api";

    ListView list;
    NewsRowAdapter adapter;
    ArrayList<HashMap<String, String>> arl;
    ArrayList<HashMap<String, String>> empty;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main);

         arl = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");

        list  =(ListView)findViewById(R.id.list);       

        adapter  = new NewsRowAdapter(getBaseContext(),ViewList.this, R.layout.row, arl);    
        list.setAdapter(adapter);
       // setListAdapter(adapter);
}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
    this.finishAffinity();
    startActivity(new Intent(ViewList.this,MainActivity.class));

}
}

2 个答案:

答案 0 :(得分:0)

更改ViewList中的代码,如下所示:

list  =(ListView)findViewById(R.id.list);

adapter  = new NewsRowAdapter(getBaseContext(),ViewList.this, R.layout.row, arl);

if(adapter.getCount()!=0){
     list.setAdapter(adapter);
}
else{
   your dialog message
}

答案 1 :(得分:0)

尝试使用length()可用的JSONArray属性。如果数组的长度大于0,则继续从中检索剩余的值,否则您可以在那里显示对话框。

@Override
protected void onPostExecute(JSONObject json) {
    // TODO Auto-generated method stub
       pDialog.dismiss();
       try {
              // Getting JSON Array from URL
           //JSONObject jobs  = json.getJSONObject(TAG_DATA);

            androids = json.getJSONArray(TAG_DATA);

           if(androids.length() > 0){



               startActivity(new Intent(MainActivity.this,Empty.class));
           }
           else
           {


            //JSONObject appt= new JSONObject(json.getString("d"));


           for(int i = 0; i < androids.length(); i++){
              JSONObject c = androids.getJSONObject(i);

              // Storing  JSON item in a Variable

              JSONObject job  = c.getJSONObject(TAG_OBJ_2);

              firstName = job.getString(TAG_PROP_FNAME);
              String lastName = job.getString(TAG_PROP_LNAME);

              JSONObject job_two  = c.getJSONObject(TAG_OBJ_1).getJSONObject("DayTimeSlot");

              String start = job_two.getString(TAG_STIME );
              String end = job_two.getString(TAG_ETIME);


            /*  String ackwardDate = job_two.getString(TAG_DATE);;
              Calendar calendar = Calendar.getInstance();
              String ackwardRipOff = ackwardDate.replace("/Date(", "").replace(")/", "");
              Long timeInMillis = Long.valueOf(ackwardRipOff);
              calendar.setTimeInMillis(timeInMillis);
              String theDate = (calendar.getTime().toGMTString());
              */
              String Ldate = job_two.getString(TAG_DATE);
              String ackwardRipOff = Ldate.replace("/Date(", "").replace(")/", "");
              Long Ldat = Long.valueOf(ackwardRipOff);
              Date date = new Date(Ldat);
              String strdate = (String) DateFormat.format("MM/dd/yy", date);


              JSONObject toHid = c.getJSONObject(TAG_OBJ_1);

              String Hid = toHid.getString(TAG_HID);

              //String date = dateConvert(Ldate);
              //long Ldate = job_two.getLong("Date");


              //String strdate = (String) DateFormat.format("MM/dd/yy h:mmaa", date);

              // Adding value HashMap key => value

              HashMap<String, String> map = new HashMap<String, String>();

              map.put(TAG_PROP_FNAME, firstName);
              map.put(TAG_PROP_LNAME, lastName);
              map.put(TAG_STIME , start);
              map.put(TAG_ETIME, end);
              map.put(TAG_DATE, strdate);
              map.put(TAG_HID, Hid);

              oslist.add(map);

              //duplicate = new JSONObject();

              Intent reult = new Intent(MainActivity.this,ViewList.class);
              //reult.putStringArrayListExtra("map", oslist);
              //startActivity(reult);


              reult.putExtra("arraylist", oslist);
              startActivityForResult(reult, 500);



              }


           dupArray = new JSONArray();
           dupArray.put(oslist);
           }



            } catch (JSONException e) {
                e.printStackTrace();
          //Intent reult = new Intent(MainActivity.this,ViewList.class);
          //reult.putStringArrayListExtra("map", oslist);
         // startActivity(reult);



      }