等待凌空响应返回json对象

时间:2019-09-14 13:24:00

标签: android android-studio httprequest android-volley android-internet

我想等待排球响应返回,然后尝试使用RequestFuture get方法解决此问题,但 “ future.get(REQUEST_TIMEOUT,TimeUnit.SECONDS)”行生成系统错误。如何解决此问题 这是我的代码

public class ApiController {
private final String server="http://192.168.1.23/";
private static ApiController api=null;
private ApiController() {
}
public static ApiController getApiController(){
    if(api==null){
        api=new ApiController();
    }
    return api;
}
public JSONObject checkConlogin(String uname, String pass, Context context){
   return getJSONObject(getresponse(server+"Conductor_login.php?uname="+uname+"&pass="+pass,context));
}
private String getresponse(String urlString,Context context){
    String line=null;
    RequestQueue queue = Volley.newRequestQueue(context);
    RequestFuture<String> future = RequestFuture.newFuture();
    StringRequest stringRequest = new StringRequest(Request.Method.GET, urlString, future, future);
    queue.add(stringRequest);
    int REQUEST_TIMEOUT = 10;
    try {
        line= future.get(REQUEST_TIMEOUT, TimeUnit.SECONDS);
    } catch (InterruptedException|ExecutionException |TimeoutException e) {
    }
  return line;
}
private JSONObject getJSONObject(String line) {

    try {
        return new JSONObject(line);
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }
}

}

导体类调用ApiController checkConlogin方法,并获取上下文,用户名和密码以获取json对象

public class Conductor {
public static int conid;

public boolean login(Context context, String username, String password) {
    JSONObject jsonObject = ApiController.getApiController().checkConlogin(username,password,context);      try {
        if("done".equalsIgnoreCase(jsonObject.getString("status"))){
            conid=Integer.valueOf(jsonObject.getString("id"));
           return true;
       }else{
            Toast.makeText(context,jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
        }
        return false;
   } catch (JSONException e) {
        e.printStackTrace();
       return false;
    }

}

}

MainActivity类调用Conductor类以使用活动上下文,用户名和密码登录响应

public class MainActivity extends AppCompatActivity {

private EditText uname,pass;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    uname=findViewById(R.id.uname);
    pass=findViewById(R.id.pass);
}

public void login(View v){
    Conductor c=new Conductor();
    if(c.login(this,uname.getText().toString(),pass.getText().toString())){
        Intent mainmenu=new Intent(MainActivity.this, MainManu.class);
        startActivity(mainmenu);
        finish();
    }
}

}

my logcast01

my logcast 02

0 个答案:

没有答案