我使用larval创建了一个身份验证API(登录和注册),并在android studio中测试了它们,它们运行良好,在连接过程中我获取了用户的所有信息。
I/onSuccess: {"status":"success","data":{"id":2,"name":"user","prenom":"user"...}
我的登录 fragment
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(LoginInterface.LOGINURL)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
LoginInterface api = retrofit.create(LoginInterface.class);
Call<String> call = api.getUserLogin(getEmailId, getPassword);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Log.i("Responsestring", response.body().toString());
Log.i("onSuccess", response.body().toString());
String jsonresponse = response.body().toString();
try {
JSONObject jsonObject = new JSONObject(jsonresponse);
if (jsonObject.getString("status").equals("success")) {
Toast.makeText(getActivity(), "Login Successfully!", Toast.LENGTH_SHORT)
.show();
Intent intent;
intent = new Intent(getActivity(), ActivityListEvents.class);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
我的登录界面
public interface LoginInterface {
String LOGINURL = "http://192.168.1.105/AnnocesPFE/public/api/";
@FormUrlEncoded
@POST("login")
Call<String> getUserLogin(
@Field("email") String email,
@Field("password") String password
);
}
我需要从登录 fragment 获取 ID 并将其用于我的个人资料 fragment ,我该怎么做?
我需要在ProfileFragment中使用它
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(UpdateProfile.UPDPRO)
.addConverterFactory(ScalarsConverterFactory.create())
.build();
UpdateProfile api = retrofit.create(UpdateProfile.class);
Call<String> call = api.UpdateUsers(getId(),name,prenom,adresse,email,numtel);
//Log.i("updateUsers: ",prenom);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Log.i("Responsestring", response.body().toString());
Log.i("onSuccess", response.body().toString());
String jsonresponse = response.body().toString();
try {
JSONObject jsonObject = new JSONObject(jsonresponse);
if (jsonObject.getString("status").equals("success")) {
Toast.makeText(getActivity(), "Update Successfully!", Toast.LENGTH_SHORT)
.show();
} else if (jsonObject.getString("status").equals("error")) {
/* new CustomToast().Show_Toast(getActivity(), view,
" " + jsonObject.getString("message"));*/
Toast.makeText(getActivity(), "Update failed!", Toast.LENGTH_SHORT)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
最佳答案
您可以将从身份验证 API 获得的响应转换为 JSONObject,然后获取您需要的值。
例如,
JSONObject authenticationData = new JSONObject(jsonResponse);
try {
int successId = authenticationData.getInt("id");
catch(JSONException e) {
e.printStackTrace();
}
然后您可以将 successId 传递给您选择的 fragment 。
了解更多关于JSONObject的信息
如果您想了解如何在 fragment 之间传递数据,请向我们展示结构和一些代码。
关于java - 获取 Json 响应 Api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60741243/