简体   繁体   English

是否在异步任务中实现警报对话框?

[英]Do i implement alert dialog in async task or not?

I am trying to show whether there is an internet connection in my Login class. 我试图显示我的Login类中是否存在Internet连接。 There is another connection manager class and this class is showing an alert dialog if there is no internet connection but I am getting confused as to where to implement the code as there is also an async task in the Login class ( attempt login) can anyone tell me where to place my code and where im going wrong? 还有另一个连接管理器类,如果没有互联网连接,该类将显示一个警告对话框,但是我对在哪里实现代码感到困惑,因为Login类中还有一个异步任务(尝试登录),任何人都可以告诉我在哪里放置我的代码,我在哪里出错?

 public class LoginActivity extends Activity implements OnClickListener {

    // flag for Internet connection status
    Boolean isInternetPresent = false;

   // Connection detector class
   ConnectionDetector cd;

   EditText username, password;
   Button login;

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

      // creating connection detector class instance
    cd = new ConnectionDetector(getApplicationContext());

    /**
     * Check Internet status button click event
     * */

    username = (EditText) findViewById(R.id.username_et);
    password = (EditText) findViewById(R.id.password_et);

    login = (Button) findViewById(R.id.login_bt);
    login.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {


            // get Internet status
            isInternetPresent = cd.isConnectingToInternet();

            // check for Internet status
            if (isInternetPresent) {
                // Internet Connection is Present
                // make HTTP requests
                showAlertDialog(LoginActivity.this, "Internet Connection",
                        "You have internet connection", true);
            } else {
                // Internet connection is not present
                // Ask user to connect to Internet
                showAlertDialog(LoginActivity.this, "No Internet Connection",
                        "You don't have internet connection.", false);
            }
            String name = username.getText().toString();
            String pass = password.getText().toString();
            new AttemptLogin().execute(name, pass);
        }


        public void showAlertDialog(Context context, String title, String message, Boolean status) {
            AlertDialog alertDialog = new AlertDialog.Builder(context).create();

            // Setting Dialog Title
            alertDialog.setTitle(title);

            // Setting Dialog Message
            alertDialog.setMessage(message);

            // 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) {
                }
            });

            // Showing Alert Message
            alertDialog.show();
        }

    });

}


private class AttemptLogin extends
        AsyncTask<String, Integer, String> {

    int success;
    String message = " ", _username, _password;

    @Override
    protected String doInBackground(String... args) {
        _username = args[0];
        _password = args[1];

        try {
            Map<String, String> params = new HashMap<String, String>();
            params.put("tag", "login");
            params.put("username", _username);
            params.put("password", _password);


            HttpUtility.sendPostRequest(params);


            String response = HttpUtility.readRespone();

            JSONObject jObj = null;

            try {

                jObj = new JSONObject(response);

                success = jObj.getInt("success");
                message = jObj.getString("message");


            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data" + e.toString());
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        HttpUtility.disconnect();
        return message;

    }

    protected void onPostExecute(String status) {

        if (status != null) {

            Toast.makeText(getBaseContext(), status, Toast.LENGTH_LONG).show();

            if (success == 1) {
                SharedPreference.store(getApplicationContext(), _username, _password);
                startActivity(new Intent(getBaseContext(), DashboardActivity.class));





            }
        }
    }
}

} }

I've made my comments within your code to helpful clarify where you should perform the logic in question. 我已在代码中添加了注释,以帮助阐明应在何处执行所讨论的逻辑。

To answer your question: You do NOT create an alert dialog from your AsyncTask. 要回答您的问题:不要从AsyncTask创建警报对话框。 The flow goes like this: 流程如下:

  1. You check for an Internet connection 您检查互联网连接
  2. If Internet connection is available, make login request 如果可以连接互联网,请发出登录请求
  3. If Internet connection is NOT available, show dialog. 如果没有Internet连接,则显示对话框。

Please let me know if you have any questions. 请让我知道,如果你有任何问题。

public class LoginActivity extends Activity implements OnClickListener {

    // flag for Internet connection status
    Boolean isInternetPresent = false;

   // Connection detector class
   ConnectionDetector cd;

   EditText username, password;
   Button login;

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

      // creating connection detector class instance
    cd = new ConnectionDetector(getApplicationContext());

    /**
     * Check Internet status button click event
     * */

    username = (EditText) findViewById(R.id.username_et);
    password = (EditText) findViewById(R.id.password_et);

    login = (Button) findViewById(R.id.login_bt);
    login.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {


            // get Internet status
            isInternetPresent = cd.isConnectingToInternet();

            // check for Internet status
            if (isInternetPresent) {

                ***********************************************
                I moved your code to show a dialog to the beginning of the
                if block where you have internet. I also changed your dialog
                to a Toast message, as others have suggested. Dialog is a little
                too heavy for this in my opinion.
                ***********************************************

                 // Internet Connection is Present
                // make HTTP requests
                // showAlertDialog(LoginActivity.this, "Internet Connection",
                //         "You have internet connection", true);
                Toast
                .makeText(this, "You have internet connection", Toast.LENGTH_LONG)
                .show();

                ***********************************************
                Assuming that your isConnectingToInternet method returns 
                the correct value, within this if statement, you know that
                you have a valid Internet connection. Go ahead and fire offf
                your AsyncTask here.                

                I moved this code from after your if / else statement to within the
                if / else statement once you verify that the device has an Internet
                connection. AGAIN: This is assuming that your isConnectingToInternet
                returns a proper value. I did not look at that code.
                **********************************************

                String name = username.getText().toString();
                String pass = password.getText().toString();
                new AttemptLogin().execute(name, pass);

            } else {

                ***********************************************
                This logic remains the same. Think about it:
                If the user doesn't have Internet connection, you can't make a login
                request.
                ***********************************************

                // Internet connection is not present
                // Ask user to connect to Internet
                showAlertDialog(LoginActivity.this, "No Internet Connection",
                        "You don't have internet connection.", false);
            }

        }


        public void showAlertDialog(Context context, String title, String message, Boolean status) {
            AlertDialog alertDialog = new AlertDialog.Builder(context).create();

            // Setting Dialog Title
            alertDialog.setTitle(title);

            // Setting Dialog Message
            alertDialog.setMessage(message);

            // 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) {
                }
            });

            // Showing Alert Message
            alertDialog.show();
        }

    });

}


private class AttemptLogin extends
        AsyncTask<String, Integer, String> {

    int success;
    String message = " ", _username, _password;

    @Override
    protected String doInBackground(String... args) {
        _username = args[0];
        _password = args[1];

        try {
            Map<String, String> params = new HashMap<String, String>();
            params.put("tag", "login");
            params.put("username", _username);
            params.put("password", _password);


            HttpUtility.sendPostRequest(params);


            String response = HttpUtility.readRespone();

            JSONObject jObj = null;

            try {

                jObj = new JSONObject(response);

                success = jObj.getInt("success");
                message = jObj.getString("message");


            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data" + e.toString());
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        HttpUtility.disconnect();
        return message;

    }

    protected void onPostExecute(String status) {

        if (status != null) {

            Toast.makeText(getBaseContext(), status, Toast.LENGTH_LONG).show();

            if (success == 1) {
                SharedPreference.store(getApplicationContext(), _username, _password);
                startActivity(new Intent(getBaseContext(), DashboardActivity.class));





            }
        }
    }
}

use this class for checking internet connectivity... 使用此类检查互联网连接...

public class CheckNetwork {
    private Context context;

    public CheckNetwork(Context context) {
        this.context = context;
    }

    public boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}

then..... 然后.....

use the this ASyncTask for login attempt. 使用此ASyncTask进行登录尝试。

public class AttemptLogin extends AsyncTask<String, Void, String> {

    private ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(LoginActivity.this);
        dialog.setMessage("Loading...");
        dialog.setCancelable(false);
        dialog.show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... arg0) {
        if (new CheckNetwork(LoginActivity.this).isNetworkAvailable() {
            // your get/post related code...
        } else {
            Toast.makeText(LoginActivity.this, "no internet!", Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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