无法从 android 应用程序的方法或其他活动中获取数据

Can't get data out of method or in other activities on android app

我正在尝试将登录应用程序的用户的数据存储在 class 中,以便我可以在所有活动中使用它的所有数据。

我遵循了几个关于可序列化的指南,但我无法让它工作。

此函数从我的 api:

调用用户对象
public void GetGame(String UID){
    String url = "https://worldapi.azurewebsites.net/api/homeracer/user/"+UID;
    final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,

            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d("tag", "jsonresponse" + response.toString());
                    try {
                        //String name = response.getString("userName");
                        currentUser.setUserId(response.getInt("userId"));
                        currentUser.setStartLat(response.getInt("startLat"));
                        currentUser.setStartLong(response.getDouble("startLong"));
                        currentUser.setEndLat(response.getDouble("endLat"));
                        currentUser.setEndLong(response.getDouble("endLong"));
                        currentUser.setUsername(response.getString("userName"));

                        startLong.setText(String.valueOf(currentUser.getStartLong()));
                        userName.setText(currentUser.getUsername());

                        //Intent sendObj = new Intent(Homescreen.this, Homescreen.class);
                        bundle = new Bundle();
                        bundle.putSerializable("userInfo", currentUser);
                        //sendObj.putExtras(bundle);
                        //startActivity(sendObj);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("error", error.toString());
                }
            }
    );
    jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
            10000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    //mRequestQueue.add(jsonObjectRequest);
    Volley.newRequestQueue(this).add(jsonObjectRequest);
}

现在,当我在 'onResponse' 方法之外的任何地方尝试从当前用户获取用户名或任何其他数据时。该字段为空。

所以我的问题是:如何设置 currentUser 对象,以便我可以在我的活动中使用它的所有字段并将其发送到其他活动。 我试过 sharedpreferences 并且它有效,但我读到的地方并不理想。

用户数据class:

public class UserData implements Serializable {
  int UserId;
  double EndLat, EndLong, StartLat, StartLong;
  String Username;
  /*public Userdata(){

     }

  public Userdata(String username, double endLat, double endLong, double startLat
                             ,double startLong, int userId){
             this.Username = username;
             this.UserId = userId;
             this.StartLat = startLat;
             this.StartLong = startLong;
             this.EndLat = endLat;
             this.EndLong = endLong;

     }*/

  public void setUserId(int _userId) {
    this.UserId = _userId;
  }

  public int getUserId() {
    return UserId;
  }

  public void setEndLat(double _endLat) {
    this.EndLat = _endLat;
  }

  public double getEndLat() {
    return EndLat;
  }

  public void setStartLat(double _startLat) {
    this.StartLat = _startLat;
  }

  public double getStartLat() {
    return StartLat;
  }

  public void setEndLong(double _endLong) {
    this.EndLong = _endLong;
  }

  public double getEndLong() {
    return EndLong;
  }

  public void setStartLong(double _startLong) {
    this.StartLong = _startLong;
  }

  public double getStartLong() {
    return StartLong;
  }

  public void setUsername(String username) {
    this.Username = username;
  }

  public String getUsername() {
    return Username;
  }
}

在 Android 中,您可以通过实现 Parcelable 接口轻松地在整个 Activity 中传递对象。

步骤是:

  • 您的 class 应该实现 Parcelable 接口。
  • 创建一个 Intent 以您想要导航的 Activity 为目标,并使用 putExtra() 方法传递您的对象。
  • 从新 Activity 中检索您的对象。

下面是您的 UserData class 实施 Parcelable。 Android Studio 可帮助您轻松完成此任务。

public class UserData implements Parcelable {
    private int UserId;
    private double EndLat, EndLong, StartLat, StartLong;
    private String Username;

    public void setUserId(int _userId) {
        this.UserId = _userId;
    }

    public int getUserId() {
        return UserId;
    }

    public void setEndLat(double _endLat) {
        this.EndLat = _endLat;
    }

    public double getEndLat() {
        return EndLat;
    }

    public void setStartLat(double _startLat) {
        this.StartLat = _startLat;
    }

    public double getStartLat() {
        return StartLat;
    }

    public void setEndLong(double _endLong) {
        this.EndLong = _endLong;
    }

    public double getEndLong() {
        return EndLong;
    }

    public void setStartLong(double _startLong) {
        this.StartLong = _startLong;
    }

    public double getStartLong() {
        return StartLong;
    }

    public void setUsername(String username) {
        this.Username = username;
    }

    public String getUsername() {
        return Username;
    }

    // Parcelable implementation bellow this line

    protected UserData(Parcel in) {
        UserId = in.readInt();
        EndLat = in.readDouble();
        EndLong = in.readDouble();
        StartLat = in.readDouble();
        StartLong = in.readDouble();
        Username = in.readString();
    }

    public static final Creator<UserData> CREATOR = new Creator<UserData>() {
        @Override
        public UserData createFromParcel(Parcel in) {
            return new UserData(in);
        }

        @Override
        public UserData[] newArray(int size) {
            return new UserData[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeInt(UserId);
        parcel.writeDouble(EndLat);
        parcel.writeDouble(EndLong);
        parcel.writeDouble(StartLat);
        parcel.writeDouble(StartLong);
        parcel.writeString(Username);
    }
}

创建 Intent:

Intent intent = new Intent(context/*your activity*/, TargetActivity.class);

现在将对象传递给意图。 intent.putExtra("your_key",yourObject); 开始你的 activity startActivity(intent).

最后从TargetActivity获取从Intent传递到这里的对象。

UserData yourObject = getIntent().getParcelableExtra("your_key");

就是这样!