登录尝试和登录已泄露窗口

时间:2014-05-29 19:19:27

标签: android

我有登录活动。这个问题让我疯狂了两天多。当我插入正确的用户名和密码时,登录成功。但是当我插入错误的用户名或密码时,应用程序会冻结。我认为我有正确的对话解雇,这是根据我在stackoverflow上搜索大多数情况下的主要漏洞  我的登录活动

package com.example.tranfer;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity implements OnClickListener {

private EditText user, pass;
private Button mSubmit, mRegister;
private String username, password;

// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

// php login script location:

// localhost :
// testing on your device
// put your local ip instead, on windows, run CMD > ipconfig
// or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL =
// "http://xxx.xxx.x.x:1234/webservice/login.php";

// testing on Emulator:private static final String LOGIN_URL =     "http://******";

// testing from a real server:
// private static final String LOGIN_URL =
// "http://www.yourdomain.com/webservice/login.php";

// JSON element ids from response of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    // setup input fields
    user = (EditText) findViewById(R.id.editusername);
    pass = (EditText) findViewById(R.id.editpassword);

    // setup buttons
    mSubmit = (Button) findViewById(R.id.signin);
    mRegister = (Button) findViewById(R.id.register);

    // register listeners
    mSubmit.setOnClickListener(this);
    mRegister.setOnClickListener(this);

}

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

    case R.id.signin:
        new AttemptLogin().execute();
        break;
    case R.id.register:
        Intent i = new Intent(this, RegistrationForm.class);
        startActivity(i);
        break;

    default:
        break;
    }
}

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

    /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Login.this);
        pDialog.setMessage("Προσπάθεια σύνδεσης...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;
        username = user.getText().toString();
        password = pass.getText().toString();
        try {
            // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("username", username));
    params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
    JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
                    params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
Log.d("Login Successful!", json.toString());
        Intent i = new Intent(Login.this, MainActivity1.class);
                finish();
                startActivity(i);
                return json.getString(TAG_MESSAGE);
            } else {
        Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);

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

        return null;

    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null) {
    Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

      }

        }

我的php文件

<?php

//load and connect to MySQL database stuff
require("config.inc.php");

if (!empty($_POST)) {
//gets user's info based off of a username.
$query = " 
        SELECT 
            id, 
            username, 
            password
        FROM users 
        WHERE 
            username = :username 
    ";

$query_params = array(
    ':username' => $_POST['username']
);

try {
    $stmt   = $db->prepare($query);
    $result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
    // For testing, you could use a die and message. 
    //die("Failed to run query: " . $ex->getMessage());

    //or just use this use this one to product JSON data:
    $response["success"] = 0;
    $response["message"] = "Database Error1. Please Try Again!";
    die(json_encode($response));

}

//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;

//fetching all the rows from the query
$row = $stmt->fetch();
if ($row) {
    //if we encrypted the password, we would unencrypt it here, but in our case we just
    //compare the two passwords
    if ($_POST['password'] === $row['password']) {
        $login_ok = true;
    }
}


if ($login_ok) {
    $response["success"] = 1;
    $response["message"] = "Login successful!";
    die(json_encode($response));
} else {
    $response["success"] = 0;
    $response["message"] = "Invalid Credentials!";
    die(json_encode($response));
}
} else {
?>
    <h1>Login</h1> 
    <form action="login.php" method="post"> 
        Username:<br /> 
        <input type="text" name="username" placeholder="username" /> 
        <br /><br /> 
        Password:<br /> 
        <input type="password" name="password" placeholder="password" value=""  /> 
        <br /><br /> 
        <input type="submit" value="Login" /> 
    </form> 
    <a href="register.php">Register</a>
<?php
}

?> 

logcat的

05-29 22:01:23.388: E/WindowManager(24822): Activity com.example.tranfer.Login has leaked window com.android.internal.policy.impl.PhoneWindow                                            $DecorView@4272a7f0 that was originally added here
05-29 22:01:23.388: E/WindowManager(24822): android.view.WindowLeaked: Activity com.example.tranfer.Login has leaked window                                             com.android.internal.policy.impl.PhoneWindow$DecorView@4272a7f0 that was originally added here
05-29 22:01:23.388: E/WindowManager(24822):     at android.view.ViewRootImpl.<init>(ViewRootImpl.java:415)
05-29 22:01:23.388: E/WindowManager(24822):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:322)
05-29 22:01:23.388: E/WindowManager(24822):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:234)
05-29 22:01:23.388: E/WindowManager(24822):     at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:153)
05-29 22:01:23.388: E/WindowManager(24822):     at android.view.Window$LocalWindowManager.addView(Window.java:559)
05-29 22:01:23.388: E/WindowManager(24822):     at android.app.Dialog.show(Dialog.java:301)
05-29 22:01:23.388: E/WindowManager(24822):     at com.example.tranfer.Login$AttemptLogin.onPreExecute(Login.java:106)
05-29 22:01:23.388: E/WindowManager(24822):     at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
05-29 22:01:23.388: E/WindowManager(24822):     at android.os.AsyncTask.execute(AsyncTask.java:534)
05-29 22:01:23.388: E/WindowManager(24822):     at com.example.tranfer.Login.onClick(Login.java:80)
05-29 22:01:23.388: E/WindowManager(24822):     at android.view.View.performClick(View.java:4262)
05-29 22:01:23.388: E/WindowManager(24822):     at android.view.View$PerformClick.run(View.java:17421)
05-29 22:01:23.388: E/WindowManager(24822):     at android.os.Handler.handleCallback(Handler.java:615)
05-29 22:01:23.388: E/WindowManager(24822):     at android.os.Handler.dispatchMessage(Handler.java:92)
05-29 22:01:23.388: E/WindowManager(24822):     at android.os.Looper.loop(Looper.java:137)
05-29 22:01:23.388: E/WindowManager(24822):     at android.app.ActivityThread.main(ActivityThread.java:4944)
05-29 22:01:23.388: E/WindowManager(24822):     at java.lang.reflect.Method.invokeNative(Native Method)
05-29 22:01:23.388: E/WindowManager(24822):     at java.lang.reflect.Method.invoke(Method.java:511)
05-29 22:01:23.388: E/WindowManager(24822):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
05-29 22:01:23.388: E/WindowManager(24822):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
05-29 22:01:23.388: E/WindowManager(24822):     at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:0)

我认为这是因为您的ProgressDialog在进入下一个活动之前没有关闭。

变化:

if (success == 1) {
    Log.d("Login Successful!", json.toString());
    Intent i = new Intent(Login.this, MainActivity1.class);
    finish();
    startActivity(i);
    return json.getString(TAG_MESSAGE);
}

要:

if (success == 1) {
    pDialog.dismiss();
    Log.d("Login Successful!", json.toString());
    Intent i = new Intent(Login.this, MainActivity1.class);
    finish();
    startActivity(i);
    return json.getString(TAG_MESSAGE);
}

如果pDialog.dismss();方法不为空,您还应该确保onDestroy()。{/ p>

答案 1 :(得分:0)

首先将以下两行从doInBackground移至onPreExecute ...

username = user.getText().toString();
password = pass.getText().toString();

...你不应该试图从doInBackground访问任何UI元素,因为它在一个单独的线程上运行到主(UI)线程。

其次,将启动MainActivity1的代码移至您的onPostExecute方法。在你关闭对话框后把它放好。