【发布时间】:2021-07-10 08:22:55
【问题描述】:
服务器连接正在后台 (AsyncTask) 和服务器响应 JSON 上工作。 我想将数据从服务器发送到其他活动,但它不工作。 我试图解决这个问题,但没有任何效果。我该如何解决这个问题? 我的代码如下:
public class LoginRequest extends AsyncTask<Void, Void, String> {
String errorMsg = LOGIN_ERROR;
String builder;
@Override
protected String doInBackground(Void... voids) {
JSONObject requestJsonObject = new JSONObject();
try {
requestJsonObject.put("email", userEmail);
requestJsonObject.put("password", userPassword);
} catch (JSONException e) {
e.printStackTrace();
}
requestQueue = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.POST,
BASE_URL,
requestJsonObject,
response -> {
errorMsg = LOGIN_SUCCESS;
Log.d(TAG, "response = " + response);
builder = response.toString();
},
error -> errorMsg = LOGIN_ERROR
);
requestQueue.add(request);
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (errorMsg.equals(LOGIN_ERROR)) {
textViewError.setText(R.string.login_failure);
} else {
Toast.makeText(getApplicationContext(), "Login Success", Toast.LENGTH_SHORT).show();
// Send data from server to UserMainActivity
Intent intent = new Intent(LoginActivity.this, UserMainActivity.class);
intent.putExtra("serverMessage", builder);
startActivity(intent);
}
}
}
【问题讨论】:
-
尝试删除 super.onPostExecute(s);
-
不,不要像@Shayan所说的那样删除
super.onPostExecute(s)。 -
你所做的并没有错。以最短的方式发布您的 json 响应,并向我们展示您如何处理
UserMainActivity中传递的变量。 -
@ZankrutParmar 我在响应侦听器中将 JSON 数据从服务器更改为字符串,并将 UserMainActivity 中的数据作为 Intent dataIntent = getIntent(); serverMessage = dataIntent.getStringExtra(SERVER_MESSAGE);
-
serverMessage 只是字符串变量。
标签: android server android-asynctask