如何将StringRequest或JsonObjectRequest的结果返回给我调用该方法的类。 在我的MainActivty中,我有一个登录按钮。当我按下它时,它将使用我的Backgroundworker.class中的StingRequest调用函数checkLogin。如何将响应返回给MainActivity进行处理或显示? 由于该方法的异步性,因此我无法在该方法的末尾使用return。我尝试在MainActivity中调用方法,但在达到Intent时总是会收到错误消息
2019-05-16 16:43:52.794 3158-3158/com.test.Test E/Error: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
执行这样的登录功能的正确方法是什么?
-MainActivity
package com.test.Test;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.test.Test.tools.BackgroundWorker;
public class MainActivity extends AppCompatActivity {
private EditText txtEditUser;
private EditText txtEditPw;
private Button btnLogin;
private Button btnRegister;
private TextView txtViewLoginfailed;
private String user;
private String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtEditUser = findViewById(R.id.txtEditUser);
txtEditPw = findViewById(R.id.txtEditPw);
btnLogin = findViewById(R.id.btnLogin);
btnRegister = findViewById(R.id.btnRegister);
txtViewLoginfailed = findViewById(R.id.txtViewLoginfailed);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
user = txtEditUser.getText().toString();
password = txtEditPw.getText().toString();
new BackgroundWorker().checkLogin(user, password, getApplicationContext());
}
});
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent register = new Intent(getApplicationContext(), Register.class);
startActivity(register);
}
});
}
public void Login(Boolean LoginOK,Context context) {
if (LoginOK) {
Intent menu = new Intent(context, Menu.class);
startActivity(menu);
} else {
txtViewLoginfailed.setText("Login failed");
}
}
}
-Backgroundworker
public class BackgroundWorker {
private Boolean LoginOK;
public void checkLogin(final String user, final String password, final Context context) {
String url = "http://192.168.0.2:80/webapp/login.php";
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
Log.d("testLogin", "3");
if (response.equals("login success")) {
LoginOK = true;
new MainActivity().Login(LoginOK, context);
} else {
Log.d("testLogin", "5");
}
} catch (Exception exc) {
exc.printStackTrace();
Log.e("Error", exc.getMessage());
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", error.getMessage());
}
}
) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_name", user);
params.put("password", password);
return params;
}
};
queue.add(sr);
}
}
答案 0 :(得分:0)
您需要的是Callback
界面。
创建新界面,例如LoginRequestCallback
:
public interface LoginRequestCallback {
void onLoginRequestSuccess();
void onLoginRequestError(String errorMessage);
}
在您的checkLogin
方法中,添加新参数LoginRequestCallback callback
:
public void checkLogin(final String user, final String password, final Context context, LoginRequestCallback callback) { ... }
然后调用与登录成功或错误相对应的方法:
public void checkLogin(final String user, final String password, final Context context) {
String url = "http://192.168.0.2:80/webapp/login.php";
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
Log.d("testLogin", "3");
if (response.equals("login success")) {
callback.onLoginRequestSuccess();
} else {
callback.onLoginRequestError("Invalid credentials");
}
} catch (Exception exc) {
exc.printStackTrace();
Log.e("Error", exc.getMessage());
callback.onLoginRequestError(exc.getMessage());
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", error.getMessage());
callback.onLoginRequestError(exc.getMessage());
}
}
) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_name", user);
params.put("password", password);
return params;
}
};
queue.add(sr);
}
从MainActivity
进行调用时,请使MainActivity
类实现此接口:
public class MainActivity extends Activity implements LoginRequestCallback {
//...
@Override
public void onLoginRequestSuccess() {
}
@Override
public void onLoginRequestError(String errorMessage) {
}
}
当您调用此方法时,将this
作为回调传递:
void onLoginButtonClicked(View v) {
String user = "Asd";
String password = "asdasd";
this.backgroundWorker.checkLogin(user, password, this, this);
}
@Override
public void onLoginRequestSuccess() {
this.Login(true, this);
}
@Override
public void onLoginRequestError(String errorMessage) {
Toast.makeText(this, errorMessage, Toast.SHORT).show();
}