2016-07-22 7 views
0

Android、PHP、MySQLを学ぶために、この基本tutorialに従っています。Android、PHP、MySQL:URLConnectionホストへのルートがありません

私が次のように私のニーズに合わせてコードを適合させています。

これまでのところすべてがうまくいっていて、アプリケーションがうまく動作し、logcatにJavaエラーが表示されないので、私のコードは正しいと思われます。私が分っている唯一の問題は、次のとおりです。

libcore.io.ErrnoException: isConnected failed: EHOSTUNREACH (No route to host) 

私はログインボタンを押すと、メソッド全体を最後まで実行します。私はWAMPを使用していますし、フォルダ "API" は、 "WWW" フォルダの下に保存され

public class LoginActivity extends AppCompatActivity { 
public static final int CONNECTION_TIMEOUT = 10000; 
public static final int READ_TIMEOUT = 15000; 
EditText emailLogin, passwordLogin; 
Button buttonLogin, buttonRegisterLink; 
TextView numberAttemptsLeft; 
int counter = 3; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.login); 
    emailLogin = (EditText)findViewById(R.id.email_login); 
    passwordLogin = (EditText)findViewById(R.id.password_login); 
    buttonLogin = (Button)findViewById(R.id.button_login); 
    buttonRegisterLink = (Button)findViewById(R.id.button_register_link); 
    numberAttemptsLeft = (TextView)findViewById(R.id.numberAttemptsLeft); 
    numberAttemptsLeft.setVisibility(View.GONE); 

    // method calls 
    login(); 
    linkToRegisterScreen(); 
} 

public void login() { 
    final String email = emailLogin.getText().toString(); 
    final String password = passwordLogin.getText().toString(); 

    buttonLogin.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View view) { 
      new AsyncLogin().execute(email,password); 
     } 
    }); 
} 

private class AsyncLogin extends AsyncTask<String, String, String> 
{ 
    ProgressDialog loading = new ProgressDialog(LoginActivity.this); 
    HttpURLConnection connection; 
    URL url = null; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     loading.setMessage("\tLoading..."); 
     loading.setCancelable(false); 
     loading.show(); 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     try { 
      url = new URL("http://myIPaddress/api/login.php"); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
      return "exception"; 
     } 
     try { 
      connection = (HttpURLConnection)url.openConnection(); 
      connection.setReadTimeout(READ_TIMEOUT); 
      connection.setConnectTimeout(CONNECTION_TIMEOUT); 
      connection.setRequestMethod("POST"); 
      connection.setDoInput(true); 
      connection.setDoOutput(true); 

      Uri.Builder builder = new Uri.Builder() 
        .appendQueryParameter("email", params[0]) 
        .appendQueryParameter("password", params[1]); 
      String query = builder.build().getEncodedQuery(); 

      OutputStream os = connection.getOutputStream(); 
      BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8")); 
      writer.write(query); 
      writer.flush(); 
      writer.close(); 
      os.close(); 
      connection.connect(); 
     } catch (IOException e1) { 
      e1.printStackTrace(); 
      return "exception"; 
     } 

     try { 
      int response_code = connection.getResponseCode(); 

      if (response_code == HttpURLConnection.HTTP_OK) { 
       InputStream input = connection.getInputStream(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(input)); 
       StringBuilder result = new StringBuilder(); 
       String line; 

       while ((line = reader.readLine()) != null) { 
        result.append(line); 
       } 
       return(result.toString()); 
      }else{ 
       return("unsuccessful"); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
      return "exception"; 
     } finally { 
      connection.disconnect(); 
     } 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     loading.dismiss(); 

     if(result.equalsIgnoreCase("true")) 
     { 
      Intent intent = new Intent(getApplicationContext(), DashboardActivity.class); 
      startActivity(intent); 
      finish(); 
     } else if (result.equalsIgnoreCase("false")){ 
      Toast.makeText(getApplicationContext(), "Invalid Email or Password.", Toast.LENGTH_LONG).show(); 
     } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) { 
      Toast.makeText(getApplicationContext(), "Something else went wrong.", Toast.LENGTH_LONG).show(); 
     } 
    } 
} 

}

は、ここに私のLoginActivity.javaコードです。 login.phpは "api"フォルダ内に保存されます。

私はこのpostで提案された解決策を試しましたが、私は運がなかった。

ありがとうございます。

EDIT:私の2つのPHPファイルのコードを参考にしてください。私はそれが到達不能になっているサーバーと間違って何か想像

configuration.php(APIの下で/含める)

<?php 
$servername = "localhost"; 
$username = "user"; 
$password = "pass"; 
$database = "db"; 

try { 
     $conn = new PDO("mysql:host = $servername; dbname = $db", $username, $password); 
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    } 
catch(PDOException $e) 
    { 
     die("Server Error."); 
    } 
?> 

(API下)login.php

<?php 
include 'configuration.php'; 

// check whether or not the email or password is set from android 
if(isset($_POST['email']) && isset($_POST['password'])) 
{ 
    // initialize variables 
    $result=''; 
    $email = $_POST['email']; 
     $password = $_POST['password']; 

    // query database 
    $sql = 'SELECT * FROM clients WHERE email = :email AND password = :password'; 
    $stmt = $conn->prepare($sql); 
     $stmt->bindParam(':email', $email, PDO::PARAM_STR); 
     $stmt->bindParam(':password', $password, PDO::PARAM_STR); 
     $stmt->execute(); 

    // if else statement 
    if($stmt->rowCount()) 
     { 
     $result="true"; 
     } 
     elseif(!$stmt->rowCount()) 
     { 
     $result="false"; 
     } 

    // send the result back to android 
    echo $result; 
} 
?> 

答えて

0

。あなたはサーバーの応答を得るか、それともエラーになりますか?例外はどこにスローされますか?

+0

エラーだけです。 java.net.ConnectException:10000ms後に/ myIPaddress(ポート80)への接続に失敗しました:isConnectedが失敗しました:EHOSTUNREACH(ホストへのルートなし) –

+0

デバイスまたはコンピュータのブラウザからURLをヒットできますか? – confusedProgrammer

+0

はい、私はそのリンクに問題はありません。私のPHPファイルについては2つの警告が表示されます。 PHPファイルを含めるために質問を編集しますか? –

関連する問題