我正在尝试为用户模型实现单例设计模式。我遇到的问题是维护一个对象,该对象存储我的应用程序中任何一点要检索的所有数据。全球对象。
我不确定应该在何处或如何实现全局用户对象。我从服务器检索JSON响应,然后在AsyncTask中从它创建一个User对象,然后通过接口将该User对象一直传递给NavigationActivity" getCreatedUser"方法
在该方法中我该怎么办?如果有什么?也许某种类型的解决方案可以查找?
这是我的用户模型,至少是其中的一部分
public class User {
static User _user;
int location_id, group_id, user_address_zip, user_refer, user_stat,
user_bnav, user_jguide, user_mbooks, user_minvent, user_mfeed,
user_mupdates, user_talert, user_tmessage, user_id;
float user_owes, user_owed;
String user_nick, user_password, user_salt, user_bday, user_title,
user_name, user_address, user_address_lat, user_address_lng,
user_address_street, user_address_street2, user_address_city,
user_address_state, user_phone, user_phone_c, user_phone_w,
user_phone_cell, user_phone_carrier, user_email, user_email_work,
user_avatar, user_signature, user_created, user_auth, user_clock,
user_onsite, user_return, user_return_to, user_company;
public User() {
}
public static User currentUser() {
if (_user == null) {
_user = new User();
}
return _user;
}
public int getUser_id() {
return user_id;
}
这是ASYNC TASK
public static class CreateUser extends AsyncTask<User, Void, User> {
Context mContext;
public interface CreateUserInterface {
public void getCreatedUser(User user);
public void getUserCreateErrorMessage(String error);
}
CreateUserInterface callback;
public CreateUser(Context context) {
// TODO Auto-generated constructor stub
this.mContext = context;
callback = (CreateUserInterface) context;
}
@Override
protected User doInBackground(User... params) {
ObjectMapper mapper = new ObjectMapper(); // create once, reuse
User user = params[0];
String url = ROUTE_USER_CREATE;
HttpPost httppost = new HttpPost(url);
HttpClient httpclient = new DefaultHttpClient();
String UserJSONResponse = null;
try {
String jsonString = mapper.writeValueAsString(user);
StringEntity m_stringEntity = new StringEntity(jsonString);
httppost.setEntity(m_stringEntity);
httppost.addHeader("Content-type", "application/json");
HttpResponse postResponse = httpclient.execute(httppost);
UserJSONResponse = EntityUtils.toString(postResponse
.getEntity());
user = mapper.readValue(UserJSONResponse, User.class);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
@Override
protected void onPostExecute(User result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//User user = new User();
Log.e("USERNAME", result.getUser_name());
callback.getCreatedUser(result);
}
}
以下是我的NavigationActivity中实现上述接口的接口方法
@Override
public void getCreatedUser(User user) {
// TODO Auto-generated method stub
//Log.e("USERNAME", user.getUser_name());
}