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

标签 java android android-asynctask connection

我试图显示我的登录类中是否有互联网连接。还有另一个连接管理器类,如果没有互联网连接,该类将显示一个警报对话框,但我对在哪里实现代码感到困惑,因为登录类中还有一个异步任务(尝试登录)任何人都可以告诉我我的代码应该放在哪里,哪里出错了?

 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));





            }
        }
    }
}

}

最佳答案

我在您的代码中发表了评论,以帮助澄清您应该在哪里执行有问题的逻辑。

回答您的问题:您不会从 AsyncTask 创建警报对话框。流程如下:

  1. 您检查互联网连接
  2. 如果互联网连接可用,请发出登录请求
  3. 如果互联网连接不可用,则显示对话框。

如果您有任何疑问,请告诉我。

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));





            }
        }
    }
}

关于java - 我是否在异步任务中实现警报对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33478095/

相关文章:

android - 从 flex mobile 中的默认相机应用程序拍摄的照片如何上传?

android - Scala + Android 集成开发环境

android - 从 Android 网络服务器下载 XML 文件

android - picasso 加载在 AsyncTask 中生成的图像

java - 如何使用 ASM 添加自定义注释

java - NoClassDefFoundError : Tomcat 7 unable to load classes from jar

java - 查找数组中第二大偶数整数的有效方法

java - Runtime.getRuntime().exec 在命令中使用 PIPE

android - 如何使用 ViewPager 或其他东西来滚动文本?

android - 循环内的 AsyncTask