1

我的内部有以下代码,MainAcitivity用于使用方法获取的用户名和密码登录到应用程序jsnrqstr.sendRequest(username, password, URL);

loginButton.setOnClickListener(
        new View.OnClickListener()
        {
            public void onClick(View view)
            {
                username = userNameBox.getText().toString();
                password = passwordBox.getText().toString();
                login_state = jsnrqstr.sendRequest(username, password, URL);
                if(login_state.equals("ok")){
                    details.setUserName(username);
                    details.setPassword(password);
                    Toast.makeText(MainActivity.this, "User Verified", Toast.LENGTH_LONG).show();
                    passwordBox.setText("");
                    Intent myIntent = new Intent(MainActivity.this, DashBoardActivity.class);
                    MainActivity.this.startActivity(myIntent);
                }else
                    Toast.makeText(MainActivity.this, "Login Unsuccessful", Toast.LENGTH_LONG).show();
                    passwordBox.setText("");
            }
        });

此方法使用以下代码接收来自 erlang 服务器的响应,该服务器使用 JSON 对象进行响应,我可以从中接收 login_state。代码jsnrqstr.sendRequest(username, password, URL);

public class JSONRequester {

String state;

public String sendRequest(final String userName, final String password, final String URL){

    new Thread(new Runnable() {
        public void run() {
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
            HttpResponse response;
            JSONObject json = new JSONObject();
            try{
                HttpPost post = new HttpPost(URL);
                post.setHeader("Content-type", "application/json");
                json.put("username", userName);
                json.put("password", password);
                StringEntity se = new StringEntity( json.toString());
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);
                /*Checking response */
                if(response!=null){
                    String temp = EntityUtils.toString(response.getEntity()); //Get the data in the entity
                    //Log.v("response", temp);
                    JsonObject o = new JsonParser().parse(temp).getAsJsonObject();
                    Log.v("response", o.get("state").toString());
                    state = o.get("state").toString();
            }}
            catch(Exception e){
                e.printStackTrace();
                //createDialog("Error", "Cannot Estabilish Connection");
            }
        }
      }).start();
          return state;
}

但我得到以下空指针异常@

if(login_state.equals("ok")){

这意味着我没有login_state正确返回上述方法的值。我认为这是因为当新的可运行线程返回值时为时已晚。我能做些什么来解决这个问题?

4

2 回答 2

1

如果您依赖返回值,您应该使用某种类型的回调,当线程完成时将开始执行您的代码。或者您可以启动新线程并等待它返回,然后再执行其他任何操作。

于 2012-09-21T06:41:37.840 回答
1

问题出在两行之间:) - 这两个:

})。开始();

<== 这里!!!

  return state;

第二个过早执行,而您的线程仍在运行。并发是解决方案。

一种常见的 Android 特定模式是 AsyncTask - http://developer.android.com/reference/android/os/AsyncTask.html - 或其类似物(线程/处理程序等)

单击时,在 onPreExecute(sendRequest 之前的代码)中启动该过程:例如,打开一个进度对话框并进行初始化。您的线程代码进入 doInBackground 方法并设置状态变量。完成后,在 onPostExecute 中,关闭进度对话框,然后继续您的登录逻辑:if(/*response*/ state!=null)...

于 2012-09-21T08:26:35.653 回答