-1

首先,在我的应用程序中,我调用了该代码:

                String login = e1.getText().toString();
                String password = e2.getText().toString();
                login = login.replace(" " , "");
                password = password.replace(" " , "");
                String a = FunkcjeAPI.zalogujSie(login, password);    
                Log.wtf("Uwaga !", a);
                Log.wtf("Uwaga !", a);
                Log.wtf("Uwaga !", a);
                Log.wtf("Uwaga !", a);
                Log.wtf("Uwaga !", a);

它应该调用FunkcjeAPI.zalogujSie()- 该方法显示 LogCat 记录并返回到我的代码,在那里我显示其他 LogCat 记录。

所以正确的顺序是:

07-27 20:51:48.610: A/Link(876): http://tymonradzik.pl/THUNDER_HUNTER/thapi.php?q=login&username=&password=&imei=
07-27 20:51:48.630: A/Link(876): {"error":"You reached daily query limit !"}  

07-27 20:51:48.330: A/Uwaga !(876): null
07-27 20:51:48.335: A/Uwaga !(876): null
07-27 20:51:48.335: A/Uwaga !(876): null
07-27 20:51:48.340: A/Uwaga !(876): null
07-27 20:51:48.345: A/Uwaga !(876): null

但是我的应用程序按该顺序返回记录:

07-27 20:51:48.330: A/Uwaga !(876): null
07-27 20:51:48.335: A/Uwaga !(876): null
07-27 20:51:48.335: A/Uwaga !(876): null
07-27 20:51:48.340: A/Uwaga !(876): null
07-27 20:51:48.345: A/Uwaga !(876): null

07-27 20:51:48.610: A/Link(876): http://tymonradzik.pl/THUNDER_HUNTER/thapi.php?q=login&username=&password=&imei=
07-27 20:51:48.630: A/Link(876): {"error":"You reached daily query limit !"}  

zalogujSie()功能代码:

public static String zalogujSie(final String nick, final String haslo)
    {
        final JSONParser jParser = new JSONParser();
        new Thread(new Runnable() {
        public void run() {     
        final String json = jParser.getJSONFromUrl("http://tymonradzik.pl/THUNDER_HUNTER/thapi.php?q=login&username=" + nick + "&password=" + haslo + "&imei=");
        Handler mainHandler = new Handler(Looper.getMainLooper());
        mainHandler.post(new Runnable() {

            @Override
            public void run() {
                JSONObject jObject;
                try {

                    jObject = new JSONObject(json);
                    Log.wtf("Link", "http://tymonradzik.pl/THUNDER_HUNTER/thapi.php?q=login&username=" + nick + "&password=" + haslo + "&imei=");
                    Log.wtf("Link", json);
                    String error = jObject.getString("error");
                    if(error == "You reached daily query limit !") { nadajWartosc("You reached daily query limit !"); }
                    if(error == "0") {nadajWartosc(jObject.getString("token"));}
                    if(error == "1") {nadajWartosc("1");}
                    if(error == "Invalid username") {nadajWartosc("Invalid username");}
                    if(error == "Invalid password") {nadajWartosc("Invalid password");}
                    if(error == "This user is already logged in !") {nadajWartosc("This user is already logged in !");}
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
                catch (NullPointerException e)
                {
                    e.printStackTrace();
                }

            }

        });   
            }}).start();

    return dozwrotu;
}

我不知道这是什么原因。现在我的应用程序无法正常工作。我试图添加wait()方法,但它没有帮助我。

@编辑

Michael Butscher给了我一个使用with的建议。它没有帮助我。也许我的代码中有错误(但编译器没有返回任何错误)?AsyncTaskProgressDialog

中的代码SignInActivit

String login = e1.getText().toString();
                String password = e2.getText().toString();
                login = login.replace(" " , "");
                password = password.replace(" " , "");
                String[] argi = {login,password};
                String a = null;    
                    a = FunkcjeAPI.zalogujSie(this, login, password);               
                Log.wtf("Uwaga !", a);
                Log.wtf("Uwaga !", a);
                Log.wtf("Uwaga !", a);
                Log.wtf("Uwaga !", a);
                Log.wtf("Uwaga !", a);
                if(a != "Invalid username" && a != "Invalid password" && a != "1")
                    t1.setText("Inserted incorrect data");
                if(a == "You reached daily query limit !")
                    t1.setText("You reached daily query limit !");
                if(a == "This user is already logged in !")
                    t1.setText("This user is already logged in !"); 

并在FunkcjeAPI

public static String zalogujSie(Activity aktywnosc, final String nick, final String haslo)
    {
        String[] argumenty = {nick, haslo};
        new Logowanie(aktywnosc).execute(argumenty);

        return dozwrotu;


    }

public static class Logowanie extends AsyncTask<String, String, String>
    {
    Activity wywolujaceActivity;
    private ProgressDialog dialog;
    public Logowanie(Activity wywolujaceActivity) {
        this.wywolujaceActivity = wywolujaceActivity;
        dialog = new ProgressDialog(wywolujaceActivity);
    }

    protected void onPreExecute() {
        this.dialog.setTitle("Please wait...");
        this.dialog.setMessage("Getting data from server");
        this.dialog.show();
    }

    @Override
    protected String doInBackground(final String... argi) {
        final JSONParser jParser = new JSONParser();
        new Thread(new Runnable() {
        public void run() {     
        final String json = jParser.getJSONFromUrl("http://tymonradzik.pl/THUNDER_HUNTER/thapi.php?q=login&username=" + argi[0] + "&password=" + argi[1] + "&imei=");
        Handler mainHandler = new Handler(Looper.getMainLooper());
        mainHandler.post(new Runnable() {

            @Override
            public void run() {
                JSONObject jObject;
                try {

                    jObject = new JSONObject(json);
                    Log.wtf("Link", "http://tymonradzik.pl/THUNDER_HUNTER/thapi.php?q=login&username=" + argi[0] + "&password=" + argi[1] + "&imei=");
                    Log.wtf("Link", json);
                    String error = jObject.getString("error");
                    if(error == "You reached daily query limit !") { nadajWartosc("You reached daily query limit !"); }
                    if(error == "0") {nadajWartosc(jObject.getString("token"));}
                    if(error == "1") {nadajWartosc("1");}
                    if(error == "Invalid username") {nadajWartosc("Invalid username");}
                    if(error == "Invalid password") {nadajWartosc("Invalid password");}
                    if(error == "This user is already logged in !") {nadajWartosc("This user is already logged in !");}
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
                catch (NullPointerException e)
                {
                    e.printStackTrace();
                }

            }

    });   
            }}).start();
        return dozwrotu;
    }

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

    }


}
4

5 回答 5

2

Android,像大多数 GUI 系统一样,通过设置一个消息队列并在主线程中运行一个循环来工作,该循环从队列中获取下一条消息然后处理它(通常通过调用一个方法),然后是下一条消息等等(这是什么类Looper并且Handler是为了)。

您的第一个片段现在(我假设)在主线程中执行。它调用zalogujSie()which 启动一个新线程,然后将 aRunnable放在此消息队列的末尾。但这只能在执行当前方法(包含您的第一个片段)并且处理队列中所有先前的消息之后运行。

于 2013-07-27T19:16:51.773 回答
2

AsyncTask 的doInBackground()方法已经在单独的线程中运行。从您的编辑中,您正在从doInBackround(). 这不是必需的。

您似乎希望执行 AsyncTask 之后的代码等待其完成。如果是这种情况,最好使用onPostExecute()AsyncTask 的方法。

SignInActivit应该看起来像:

String login = e1.getText().toString();
String password = e2.getText().toString();
login = login.replace(" " , "");
password = password.replace(" " , "");

// Now, execute your AsyncTask, no need for `zalogujSie()`
new Logowanie(this, login, password).execute();

您不需要调用的中间步骤zalogujSie()。您可以将login&password作为参数传递给构造函数。AsyncTask 为:

public static class Logowanie extends AsyncTask<Void, Void, Void> {

    Activity wywolujaceActivity;
    private ProgressDialog dialog;
    private String user, pass, error;

public Logowanie(Activity wywolujaceActivity, login, password) {
    this.wywolujaceActivity = wywolujaceActivity;
    dialog = new ProgressDialog(wywolujaceActivity);

    this.user = login;
    this.pass = password;
}

protected void onPreExecute() {
    this.dialog.setTitle("Please wait...");
    this.dialog.setMessage("Getting data from server");
    this.dialog.show();
}

@Override
protected String doInBackground(Void... nothing) {

    error = "";

    final JSONParser jParser = new JSONParser();        

    final String json = jParser.getJSONFromUrl("http://tymonradzik.pl/THUNDER_HUNTER/thapi.php?q=login&username=" + user + "&password=" + pass + "&imei=");

    JSONObject jObject;

    try {
        jObject = new JSONObject(json);

        Log.wtf("Link", "http://tymonradzik.pl/THUNDER_HUNTER/thapi.php?q=login&username=" + user + "&password=" + pass + "&imei=");

        Log.wtf("Link", json);

        error = jObject.getString("error");

        if(error.equals("You reached daily query limit !")) { nadajWartosc("You reached daily query limit !"); }

        if(error.equals("0")) {nadajWartosc(jObject.getString("token"));}

        if(error.equals("1")) {nadajWartosc("1");}

        if(error.equals("Invalid username")) {nadajWartosc("Invalid username");}

        if(error.equals("Invalid password")) {nadajWartosc("Invalid password");}

        if(error.equals("This user is already logged in !")) {nadajWartosc("This user is already logged in !");}

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

    return null;
}

@Override
protected void onPostExecute(Void result) {
    if (dialog != null && dialog.isShowing()) {
        dialog.dismiss();
    }

    Log.wtf("Uwaga !", a);
    Log.wtf("Uwaga !", a);
    Log.wtf("Uwaga !", a);
    Log.wtf("Uwaga !", a);
    Log.wtf("Uwaga !", a);

    // You had an "and"ing these conditions instead of "or"ing which would always return false.      
    if(error.equals("Invalid username") || error.equals("Invalid password") || error.equals("1"))
        t1.setText("Inserted incorrect data");

    if(error.equals("You reached daily query limit !"))
        t1.setText("You reached daily query limit !");

    if(error.equals("This user is already logged in !"))
        t1.setText("This user is already logged in !"); 

}

}

于 2013-07-30T22:34:57.337 回答
1

您的网络请求与您声明的日志记录异步发生。要解决此问题,您需要等到网络任务完成。一个简单的方法是使用droidQuery库:

String login = e1.getText().toString();
String password = e2.getText().toString();
login = login.replace(" " , "");
password = password.replace(" " , "");
$.ajax(new AjaxOptions().url("http://tymonradzik.pl/THUNDER_HUNTER/thapi.php?q=login&username=" + login + "&password=" + password + "&imei=")
                        .dataType("json")
                        .type("GET")
                        .success(new Function() {
                            @Override
                            public void invoke($ droidQuery, Object... params) {
                                //the request was successful
                                String a = params[0].toString();
                                Log.wtf("Uwaga !", a);//This will print what you are expecting
                            }
                        })
                        .error(new Function() {
                            @Override
                            public void invoke($ droidQuery, Object... params) {
                                //there was an error
                                AjaxError error = (AjaxError) params[0];
                                Log.e("Uwaga !", "Error " + error.status + ": " + error.reason);
                            }
                        })
                        .complete(new Function() {
                            @Override
                            public void invoke($ droidQuery, Object... params) {
                                //your network request has completed
                            }
                        }));
于 2013-07-31T21:02:00.950 回答
0

您的 zalogujSie 方法使用新线程,因此该方法异步运行......此时不能保证顺序。

于 2013-07-27T19:37:08.010 回答
0

您可以在线程开始之前 wait() 一个对象,

在线程内部,当它结束时,通知()该对象。

原来的线程可以继续进行

于 2013-08-01T11:35:47.200 回答