簡體   English   中英

Android應用無法連接到互聯網

[英]Android app does not connect to internet

我正在嘗試創建一個需要登錄/注冊的android應用程序,但沒有收到任何錯誤,但它無法連接到互聯網。 我有一個部分,當按下注冊按鈕時,應用會顯示“ Checking network”(檢查網絡),但它只是卡在那上面而永不動彈,我不知道這是什么問題。 我是Java的新手,所以它可能真的很簡單,在此先感謝您提供的任何幫助或提示!

這是我的register.java

public class Register extends Activity {

/**
 *  JSON Response node names.
 **/

private static String KEY_Success = "Success";
private static String KEY_Client_ID = "Client_ID";
private static String KEY_Name = "Name";
private static String KEY_Email = "Email";
private static String KEY_Username = "Username";
private static String KEY_Password = "Password";
private static String KEY_ERROR = "error";

/**
 * Defining layout items.
 **/

EditText inputName;
EditText inputUsername;
EditText inputEmail;
EditText inputPassword;
Button btnRegister;
TextView registerErrorMsg;

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);

    /**
     * Defining all layout items
     **/
    inputName = (EditText) findViewById(R.id.name);
    inputUsername = (EditText) findViewById(R.id.uname);
    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.pword);
    btnRegister = (Button) findViewById(R.id.register);
    registerErrorMsg = (TextView) findViewById(R.id.register_error);

  /**
  * Button which Switches back to the login screen on clicked
  **/

    Button login = (Button) findViewById(R.id.bktologin);
    login.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent myIntent = new Intent(view.getContext(), Login.class);
            startActivityForResult(myIntent, 0);
            finish();
        }

    });

    /**
     * Register Button click event.
     * A Toast is set to alert when the fields are empty.
     * Another toast is set to alert Username must be 5 characters.
     **/

    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if (  ( !inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) && ( !inputName.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
            {
                if ( inputUsername.getText().toString().length() > 4 ){
                    NetAsync(view);

                }
                else
                {
                    Toast.makeText(getApplicationContext(),
                            "Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
                }
            }
            else
            {
                Toast.makeText(getApplicationContext(),
                        "One or more fields are empty", Toast.LENGTH_SHORT).show();
            }
        }
    });
}
/** I THINK THE PROBLEM IS AROUND THIS AREA!
 * Async Task to check whether internet connection is working
 **/

private class NetCheck extends AsyncTask
{
    private ProgressDialog nDialog;

    @Override
    protected Object doInBackground(Object[] params) {
        return null;
    }

    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        nDialog = new ProgressDialog(Register.this);
        nDialog.setMessage("Loading, please be patient...");
        nDialog.setTitle("Checking Network");
        nDialog.setIndeterminate(false);
        nDialog.setCancelable(true);
        nDialog.show();
    }


    protected Boolean doInBackground(String... args){

    /**
    * Gets current device state and checks for working internet connection by                 trying Google.
    **/
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            try {
                URL url = new URL("http://www.google.com");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(3000);
                urlConnection.connect();
                if (urlConnection.getResponseCode() == 200)
                {
                    return true;
                }
            }
            catch (MalformedURLException e1)
            {
                e1.printStackTrace();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return false;

    }

    protected void onPostExecute(Boolean th){

        if(th == true){
            nDialog.dismiss();
            new ProcessRegister().execute();
        }
        else{
            nDialog.dismiss();
            registerErrorMsg.setText("Error in Network Connection");
        }
    }
}

private class ProcessRegister extends AsyncTask {

    /**
     * Defining Process dialog
     **/
    private ProgressDialog pDialog;

    String email,password,name,uname;

    @Override
    protected Object doInBackground(Object[] params) {
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        inputUsername = (EditText) findViewById(R.id.uname);
        inputPassword = (EditText) findViewById(R.id.pword);
        name = inputName.getText().toString();
        email = inputEmail.getText().toString();
        uname= inputUsername.getText().toString();
        password = inputPassword.getText().toString();
        pDialog = new ProgressDialog(Register.this);
        pDialog.setTitle("Contacting Servers");
        pDialog.setMessage("Registering ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }


    protected JSONObject doInBackground(String... args) {

        UserFunctions userFunction = new UserFunctions();
        JSONObject json = userFunction.registerUser(name, email, uname, password);

        return json;

    }

    protected void onPostExecute(JSONObject json) {
        /**
         * Checks for success message.
         **/
        try {
            if (json.getString(KEY_Success) != null) {
                registerErrorMsg.setText("");
                String res = json.getString(KEY_Success);

                String red = json.getString(KEY_ERROR);

                if(Integer.parseInt(res) == 1){
                    pDialog.setTitle("Getting Data");
                    pDialog.setMessage("Loading Info");

                    registerErrorMsg.setText("Successfully Registered");

                    DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                    JSONObject json_user = json.getJSONObject("user");

                    /**
                     * Removes all the previous data in the SQlite database
                     **/

                    UserFunctions logout = new UserFunctions();
                    logout.logoutUser(getApplicationContext());
                    db.addUser(json_user.getString(KEY_Name),json_user.getString(KEY_Email),json_user.getString(KEY_Username));
                    /**
                     * Stores registered data in SQlite Database
                     * Launch Registered screen
                     **/

                    Intent registered = new Intent(getApplicationContext(), Registered.class);

                    /**
                     * Close all views before launching Registered screen
                     **/
                    registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    pDialog.dismiss();
                    startActivity(registered);

                    finish();
                }

                else if (Integer.parseInt(red) ==2){
                    pDialog.dismiss();
                    registerErrorMsg.setText("User already exists");
                }
                else if (Integer.parseInt(red) ==3){
                    pDialog.dismiss();
                    registerErrorMsg.setText("Invalid Email id");
                }

            }

            else{
                pDialog.dismiss();

                registerErrorMsg.setText("Error occured in registration");
            }

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

        }
    }}
public void NetAsync(View view){
    new NetCheck().execute();
}}

我剛剛注意到了這一點:

/**
 *   The "doInBackground" is not being used" I don't know what that means.
 **/
protected Boolean doInBackground(String... args){

    /**
    * Gets current device state and checks for working internet connection by trying Google.
    **/
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnected()) {
            try {
                URL url = new URL("http://www.google.com");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(3000);
                urlConnection.connect();
                if (urlConnection.getResponseCode() == 200)
                {
                    return true;
                }
            }
            catch (MalformedURLException e1)
            {
                e1.printStackTrace();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return false;

    }
    /**
     *   The "onPostExecute" is not being used" I don't know what that means.
     **/
    protected void onPostExecute(Boolean th) 
    {

        if(th == true){
            nDialog.dismiss();
            new ProcessRegister().execute();
        }
        else{
            nDialog.dismiss();
            registerErrorMsg.setText("Error in Network Connection");
        }
    }

您有多種方法稱為:

protected Object doInBackground(Object[] params)

protected Boolean doInBackground(String... args)

您需要刪除一個空的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM