在android中使用Else和if else执行

时间:2015-03-13 10:49:01

标签: java android if-statement toast

在soap URL中尝试在SQL服务器中插入数据时,我在互联网没有连接时做了一个干杯,如果它连接了它就插入数据和"注册数据"将显示toast消息。

如果存在,它会检查WiFi连接并且成功注册" reg成功"     如果没有WiFi,它会同时发送消息(包括reg消息。)。

但在我的情况下,当互联网关闭时,已经显示了两个烘烤。

 public class MainActivity extends Fragment{


        private static final String SOAP_ACTION = "http://tempuri.org/InsertAuction";

        private static final String OPERATION_NAME = "InsertAuction";

        private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";

       private static final String SOAP_ADDRESS = "http://192.168.1.11/service.asmx";

       final static int REGCODE=100;

       boolean timeoutexcep=false,httpexcep=false,generalexcep=false;


        //private ImageView pd = null;
        EditText boatno,amounts,rates,weights;
        TextView daty;
        AutoCompleteTextView buyerno;
        Button submit;

        HttpTransportSE httpTransport;
        SoapSerializationEnvelope envelope;
        ProgressDialog progress;
        Object response;


        private long date;
        private DateFormat format;
    String currentDateandTime;

        private static final String TAG = "Debug";

        private static final boolean D = false;
        private Boolean flag = false;

        ProgressBar pb;

          Boolean isConnectionExist = false;

            // Connection detector class
            WIFIInternetConnectionDetector cd;

        @Override
        public View onCreateView(LayoutInflater inflater,
                @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            // TODO Auto-generated method stub
    View rootView = inflater.inflate(R.layout.activity_main, container, false);


            progress = new ProgressDialog(getActivity());

            boatno= (EditText)rootView. findViewById (R.id.boatno);
            daty= (TextView)rootView. findViewById (R.id.daty);
            buyerno= (AutoCompleteTextView)rootView. findViewById (R.id.buyerno);
            amounts= (EditText)rootView. findViewById (R.id.amount);
            submit= (Button)rootView. findViewById (R.id.submit);




            String[] names = getResources().
                   getStringArray(R.array.names);
                   ArrayAdapter adapter = new ArrayAdapter
                   (getActivity(),android.R.layout.simple_list_item_1,names);

                   buyerno.setThreshold(1);
                       buyerno.setAdapter(adapter);


                     SimpleDateFormat datef = new SimpleDateFormat("dd/MM/yyyy");

                    String currentDateandTime = datef.format(new Date(date));


                    Calendar ca = Calendar.getInstance();
                    SimpleDateFormat  format = new SimpleDateFormat("dd/MM/yyyy");  
                    try {  
                        daty.setText(format.format(ca.getTime()));

                    } catch (ParseException e) {
                        e.printStackTrace();  
                    }


                    wificonn();


    submit.setOnClickListener(new OnClickListener() {

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

            String a=boatno.getText().toString();
            String b=buyerno.getText().toString();
            String c=amounts.getText().toString();

            if(a.matches("")||(b.matches("")||(c.matches(""))))
                    {
                Toast.makeText(getActivity(), "Empty Values cannot be added",Toast.LENGTH_LONG).show();
                    }
            else
            {

                sqllite();


    SoapObject request=new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);

     String Boatnum= boatno.getText().toString();
     String Buyername=buyerno.getText().toString();
    // String rate=     rates.getText().toString();
    // String weight=       weights.getText().toString();
     String amount=     amounts.getText().toString();



                request.addProperty("Boatnum",Boatnum);
                request.addProperty("Buyername",Buyername);
    //          request.addProperty("rate",rate);
    //          request.addProperty("weight",weight);
                request.addProperty("amount",amount);


                //request.addProperty("Photo",data);



                            envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
                            envelope.dotNet=true;
                            envelope.setOutputSoapObject(request);

                            httpTransport = new HttpTransportSE(SOAP_ADDRESS);

                            try {

                                 serviceCall();

                            } catch (Exception exception) {


                                //Toast.makeText(getActivity(), "Registered Successfully", Toast.LENGTH_LONG).show();

                            }
            //Toast.makeText(getActivity(), "Registered Successfully", Toast.LENGTH_LONG).show();

                        }

    //else if(location.getText().toString().matches("null,null,null"))
    //{
    //  Toast.makeText(getApplicationContext(), "Move Some Other Place to Find Your Location", Toast.LENGTH_LONG).show();
    //}
    //    
    //    else if(location.getText().toString().matches(""))
    //    {
    //      Toast.makeText(getApplicationContext(), "Empty Values cannot be Considered", Toast.LENGTH_LONG).show();
    //    }
    //    else
    //    {
    //      
    //    }
        }



    });
    return rootView;


         }


    private void wificonn() {
            // TODO Auto-generated method stub

        cd = new WIFIInternetConnectionDetector(getActivity());
         isConnectionExist = cd.checkMobileInternetConn();

         // check for Internet status
         if (isConnectionExist) {

             //submit.setVisibility(View.VISIBLE);
             // Internet Connection exists
    //         showAlertDialog(getActivity(), "Internet Connection",
    //                 "Your device has WIFI internet access", true);


         } else {
             // Internet connection doesn't exist
             showAlertDialog(getActivity(), "No Internet Connection",
                     "Your device doesn't have WIFI internet access", false);

             //submit.setVisibility(View.INVISIBLE);

             Toast.makeText(getActivity(), "No Internet Connection", Toast.LENGTH_LONG).show();
         }
        }


         @SuppressWarnings("deprecation")
        public void showAlertDialog(Context context, String title, String message, Boolean status) {
        // TODO Auto-generated method stub

        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

         alertDialog.setTitle("Wifi Connection");

         // Setting Dialog Message
         alertDialog.setMessage("Your device doesn't have WIFI internet access,Please switch on Your wifi and then open your application");

    //     // Setting alert dialog icon
    //     alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

         // Setting OK Button
         alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int which) {


                 Intent intent = new Intent(Intent.ACTION_MAIN);
                 intent.addCategory(Intent.CATEGORY_HOME);
                 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                 startActivity(intent);  


             }
         });

         // Showing Alert Message
         alertDialog.show();




    }


    protected void sqllite() {
            // TODO Auto-generated method stub

          Database db1=new Database(getActivity());
            SQLiteDatabase sb1=db1.getReadableDatabase();

          sb1.execSQL("insert into Auction(boname,bname,amount,daty)values('"+boatno.getText().toString()+"','"+buyerno.getText().toString()+"','"+amounts.getText().toString()+"','"+daty.getText().toString() +"')");
          //Toast.makeText(getActivity(),"Registered Successfully!",Toast.LENGTH_SHORT).show();

         // Toast.makeText(getActivity(), "Registered Successfully",Toast.LENGTH_LONG).show();

    //      boatno.setText("");
    //      buyerno.setText("");
    //      amounts.setText("");

        }


    void serviceCall() {

            progress.setMessage("Please wait...");
            progress.show();

            new AsyncTask<Void, Void, Void>() {

                @Override
                protected Void doInBackground(Void... params) {
                    try {

                        httpTransport.call(SOAP_ACTION, envelope);

                        response = envelope.getResponse();
                    }
                        catch(SocketTimeoutException e){
                            timeoutexcep=true;
                            e.printStackTrace();
                        }

                        catch(ConnectException e){
                            httpexcep=true;
                            e.printStackTrace();
                            }
                            catch (Exception e) {
                            generalexcep=true;
                            e.printStackTrace();
                            }
                    return null;
                }


                @Override
                protected void onPostExecute(Void result) {
                    String str = "";



                    if(timeoutexcep){
                        Toast.makeText(getActivity(), "Unable to connect to server, Please try again later",Toast.LENGTH_LONG).show();
                        }
                    else if(httpexcep){
                        Toast.makeText(getActivity(), "Check Your Internet Connection",Toast.LENGTH_LONG).show();


                        }



                        if (progress != null)

                            progress.dismiss();

                        timeoutexcep=false;httpexcep=false;generalexcep=false;

                    if (response==null) {


                        Toast.makeText(getActivity(), "Registered Successfully",Toast.LENGTH_LONG).show();

                        boatno.setText("");
                        buyerno.setText("");
                        amounts.setText("");


                    }


                }   
            }.execute();

        }   




    }

In soap URL  tried to insert data's in SQL server, i did a toast when internet is not connected and if its connected it insert the data and "Register data" toast  message will be displayed.

    It's checking WiFi connection if exists it toasts the message"reg successfully"
    and if not have a WiFi it toasts both message(including reg message also.).

    But in my case the both toasted has been displayed when internet is off.


           \\   But in my case the both toasted has been displayed when internet is off.

1 个答案:

答案 0 :(得分:0)

根据你的代码,将显示两个祝酒词。我猜你错过了最后一个块。我猜这个代码应该在其他区块内。 :-) 喜欢这个

     public class MainActivity extends Fragment{


    private static final String SOAP_ACTION = "http://tempuri.org/InsertAuction";

    private static final String OPERATION_NAME = "InsertAuction";

    private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";

   private static final String SOAP_ADDRESS = "http://192.168.1.11/service.asmx";

   final static int REGCODE=100;

   boolean timeoutexcep=false,httpexcep=false,generalexcep=false;


    //private ImageView pd = null;
    EditText boatno,amounts,rates,weights;
    TextView daty;
    AutoCompleteTextView buyerno;
    Button submit;

    HttpTransportSE httpTransport;
    SoapSerializationEnvelope envelope;
    ProgressDialog progress;
    Object response;


    private long date;
    private DateFormat format;
String currentDateandTime;

    private static final String TAG = "Debug";

    private static final boolean D = false;
    private Boolean flag = false;

    ProgressBar pb;

      Boolean isConnectionExist = false;

        // Connection detector class
        WIFIInternetConnectionDetector cd;

    @Override
    public View onCreateView(LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.activity_main, container, false);


        progress = new ProgressDialog(getActivity());

        boatno= (EditText)rootView. findViewById (R.id.boatno);
        daty= (TextView)rootView. findViewById (R.id.daty);
        buyerno= (AutoCompleteTextView)rootView. findViewById (R.id.buyerno);
        amounts= (EditText)rootView. findViewById (R.id.amount);
        submit= (Button)rootView. findViewById (R.id.submit);




        String[] names = getResources().
               getStringArray(R.array.names);
               ArrayAdapter adapter = new ArrayAdapter
               (getActivity(),android.R.layout.simple_list_item_1,names);

               buyerno.setThreshold(1);
                   buyerno.setAdapter(adapter);


                 SimpleDateFormat datef = new SimpleDateFormat("dd/MM/yyyy");

                String currentDateandTime = datef.format(new Date(date));


                Calendar ca = Calendar.getInstance();
                SimpleDateFormat  format = new SimpleDateFormat("dd/MM/yyyy");  
                try {  
                    daty.setText(format.format(ca.getTime()));

                } catch (ParseException e) {
                    e.printStackTrace();  
                }


                wificonn();


submit.setOnClickListener(new OnClickListener() {

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

        String a=boatno.getText().toString();
        String b=buyerno.getText().toString();
        String c=amounts.getText().toString();

        if(a.matches("")||(b.matches("")||(c.matches(""))))
                {
            Toast.makeText(getActivity(), "Empty Values cannot be added",Toast.LENGTH_LONG).show();
                }
        else
        {

            sqllite();


SoapObject request=new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);

 String Boatnum= boatno.getText().toString();
 String Buyername=buyerno.getText().toString();
// String rate=     rates.getText().toString();
// String weight=       weights.getText().toString();
 String amount=     amounts.getText().toString();



            request.addProperty("Boatnum",Boatnum);
            request.addProperty("Buyername",Buyername);
//          request.addProperty("rate",rate);
//          request.addProperty("weight",weight);
            request.addProperty("amount",amount);


            //request.addProperty("Photo",data);



                        envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
                        envelope.dotNet=true;
                        envelope.setOutputSoapObject(request);

                        httpTransport = new HttpTransportSE(SOAP_ADDRESS);

                        try {

                             serviceCall();

                        } catch (Exception exception) {


                            //Toast.makeText(getActivity(), "Registered Successfully", Toast.LENGTH_LONG).show();

                        }
        //Toast.makeText(getActivity(), "Registered Successfully", Toast.LENGTH_LONG).show();

                    }

//else if(location.getText().toString().matches("null,null,null"))
//{
//  Toast.makeText(getApplicationContext(), "Move Some Other Place to Find Your Location", Toast.LENGTH_LONG).show();
//}
//    
//    else if(location.getText().toString().matches(""))
//    {
//      Toast.makeText(getApplicationContext(), "Empty Values cannot be Considered", Toast.LENGTH_LONG).show();
//    }
//    else
//    {
//      
//    }
    }



});
return rootView;


     }


private void wificonn() {
        // TODO Auto-generated method stub

    cd = new WIFIInternetConnectionDetector(getActivity());
     isConnectionExist = cd.checkMobileInternetConn();

     // check for Internet status
     if (isConnectionExist) {

         //submit.setVisibility(View.VISIBLE);
         // Internet Connection exists
//         showAlertDialog(getActivity(), "Internet Connection",
//                 "Your device has WIFI internet access", true);


     } else {
         // Internet connection doesn't exist
         showAlertDialog(getActivity(), "No Internet Connection",
                 "Your device doesn't have WIFI internet access", false);

         //submit.setVisibility(View.INVISIBLE);

         Toast.makeText(getActivity(), "No Internet Connection", Toast.LENGTH_LONG).show();
     }
    }


     @SuppressWarnings("deprecation")
    public void showAlertDialog(Context context, String title, String message, Boolean status) {
    // TODO Auto-generated method stub

    AlertDialog alertDialog = new AlertDialog.Builder(context).create();

     alertDialog.setTitle("Wifi Connection");

     // Setting Dialog Message
     alertDialog.setMessage("Your device doesn't have WIFI internet access,Please switch on Your wifi and then open your application");

//     // Setting alert dialog icon
//     alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

     // Setting OK Button
     alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {


             Intent intent = new Intent(Intent.ACTION_MAIN);
             intent.addCategory(Intent.CATEGORY_HOME);
             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             startActivity(intent);  


         }
     });

     // Showing Alert Message
     alertDialog.show();




}


protected void sqllite() {
        // TODO Auto-generated method stub

      Database db1=new Database(getActivity());
        SQLiteDatabase sb1=db1.getReadableDatabase();

      sb1.execSQL("insert into Auction(boname,bname,amount,daty)values('"+boatno.getText().toString()+"','"+buyerno.getText().toString()+"','"+amounts.getText().toString()+"','"+daty.getText().toString() +"')");
      //Toast.makeText(getActivity(),"Registered Successfully!",Toast.LENGTH_SHORT).show();

     // Toast.makeText(getActivity(), "Registered Successfully",Toast.LENGTH_LONG).show();

//      boatno.setText("");
//      buyerno.setText("");
//      amounts.setText("");

    }


void serviceCall() {

        progress.setMessage("Please wait...");
        progress.show();

        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                try {

                    httpTransport.call(SOAP_ACTION, envelope);

                    response = envelope.getResponse();
                }
                    catch(SocketTimeoutException e){
                        timeoutexcep=true;
                        e.printStackTrace();
                    }

                    catch(ConnectException e){
                        httpexcep=true;
                        e.printStackTrace();
                        }
                        catch (Exception e) {
                        generalexcep=true;
                        e.printStackTrace();
                        }
                return null;
            }


            @Override
            protected void onPostExecute(Void result) {
                String str = "";



                if(timeoutexcep){
                    Toast.makeText(getActivity(), "Unable to connect to server, Please try again later",Toast.LENGTH_LONG).show();
    if (progress != null)

                        progress.dismiss();
                    }
                else if(httpexcep){
                    Toast.makeText(getActivity(), "Check Your Internet Connection",Toast.LENGTH_LONG).show();
         if (progress != null)

                        progress.dismiss();

                    }else{



                    if (progress != null)

                        progress.dismiss();

                    timeoutexcep=false;httpexcep=false;generalexcep=false;

                if (response==null) {


                    Toast.makeText(getActivity(), "Registered Successfully",Toast.LENGTH_LONG).show();

                    boatno.setText("");
                    buyerno.setText("");
                    amounts.setText("");
     }

                }


            }   
        }.execute();

    }   




}