值未分配给Responselistener中的变量

时间:2017-01-11 21:43:44

标签: java android mysql

所以,我正在尝试在androidstudio中构建和应用程序,我想从mysql数据库中检索一些数据,并在应用程序中使用它。我在线使用PHP脚本,并使用响应服务器来检索数据。整个部分正在发挥作用。但是,当我将检索到的值(在JSON对象中称为ID)分配给名为entries的String变量时,它不喜欢保存它或其他东西。当我调用setData()中的值时,它返回null。有人可以对此有所了解吗?

public class MainActivity extends AppCompatActivity {

EditText editText;

public String entries;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

editText = (EditText) findViewById(R.id.text);

getData();
setData();

}

public void getData(){
    Response.Listener<String> responseListenerCount = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("JSON Parser", response);
            try {
                JSONObject jsonResponse = new JSONObject(response);
                boolean success = jsonResponse.getBoolean("success");
                if (success) {



                entries = jsonResponse.getString("ID"); // HERE THE RETRIEVED VALUE IS ASSIGNED TO VARIABLE ENTRIES
                Toast.makeText(getApplicationContext(), " Retrieving success ", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), " Retrieving failed ", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // HERE THAT VALUE IS NULL AGAIN
    }
};
CountRequest countRequest = new CountRequest(responseListenerCount);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(countRequest);

}

public void setData(){
    editText.setText(entries);
}}

这是在requestqueue中调用的countRequest.java。再次;这部分工作正常,所以它并不真正相关。

public class CountRequest extends StringRequest {

private static final String LOGIN_REQUEST_URL = "*************";
private Map<String, String> params;

public CountRequest(Response.Listener<String> listener){
    super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
    params = new HashMap<>();
}

@Override
public Map<String, String> getParams() {
    return params;
}}

1 个答案:

答案 0 :(得分:0)

我已尝试过您的代码,但从我的角度来看,它运作良好。我使用过这个脚本:

public class MainActivity extends AppCompatActivity {

EditText editText;

public String entries="test";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editText = (EditText) findViewById(R.id.text);

    getData();
    System.out.println(entries); //here id null or in my case "test"
    setData();


}

public void getData(){
    Response.Listener<String> responseListenerCount = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d("JSON Parser", response);
            try {
                JSONObject jsonResponse = new JSONObject(response);
                int success = jsonResponse.getInt("success");
                if (success==1) {



                    entries = jsonResponse.getString("user_id"); //geting user id
                   System.out.println(entries);
                    Toast.makeText(getApplicationContext(), " Retrieving success ", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), " Retrieving failed ", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            System.out.println(entries); //id is still there
            setData();
        }
    };
    CountRequest countRequest = new CountRequest(responseListenerCount);
    RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
    queue.add(countRequest);
   System.out.println(entries); //here id null or in my case "test"
}

public void setData(){
    editText.setText(entries);
}}


public class CountRequest extends StringRequest {

private static final String LOGIN_REQUEST_URL = "http://mypage.com/login_user.php?login=a&password=b";
private Map<String, String> params;

public CountRequest(Response.Listener<String> listener){
    super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
    params = new HashMap<>();
}

@Override
public Map<String, String> getParams() {
    return params;
}}


<?php

define('DB_USER', "*******"); // db user
define('DB_PASSWORD', "*******"); // db password 
define('DB_DATABASE', "*******"); // database name
define('DB_SERVER', "localhost"); // db server

class DB_CONNECT {

function __construct() {
    $this->connect();
}

function __destruct() {
    $this->close();
}

function connect() {

    $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());

    $db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());

    return $con;
}


function close() {
    mysql_close();
}

}

?>


<?php

$response = array();

if (isset($_GET['login']) && isset($_GET['password'])) {

$login = $_GET['login'];
$password = $_GET['password'];

require_once __DIR__ . '/db_connect.php';

$db = new DB_CONNECT();


$checkUser = mysql_query("Select * FROM user where login = '$login'");

 if(mysql_num_rows($checkUser)>0){

       $result = mysql_fetch_array($checkUser);
       $userpassword = $result["password"];
       $user_id = $result["user_id"];

       $response["success"] = 1;
       $response["message"] = $userpassword;
       $response["user_id"] = $user_id;
       echo json_encode($response);
 }

 else{
       $response["success"] = 0;
       $response["message"] = "User not found";
       echo json_encode($response);
 }
 }
else {
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";

echo json_encode($response);
}

?>

我认为如果你收到错误,那么它就在LOGIN_REQUEST_URL / params或PHP脚本中,就像你要求我从DB获取数据一样。虽然在这种情况下onCreate方法中的setData()将始终返回null。您正在设置&#39;条目&#39;的值。关于在后台工作的响应。因此,您的代码将来到GetData()向服务器发送请求并转到下一个命令setData(),而不是等待下载的信息。