- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我想保存一个自定义对象myObject
在共享首选项中。此自定义对象的位置 ArrayList<anotherCustomObj>
.这anotherCustomObj
有主要变量。
两者都是 myObject
和 anotherCustomObj
可打包。
我尝试使用下面的代码将其转换为字符串并保存:
String myStr = gson.toJson(myObject);
editor.putString(MY_OBJ, myStr);
但它给出了 RunTimeException。
编辑: 下面是 logcat 屏幕截图。
另一个 CustomObj 实现:
package com.objectlounge.ridesharebuddy.classes;
import java.io.File;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Parcel;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.util.Log;
import com.google.gson.annotations.SerializedName;
import com.objectlounge.ridesharebuddy.R;
public class RS_SingleMatch implements Parcelable {
private static final String RIDESHARE_DIRECTORY = "RideShareBuddy";
private static final String TAG = "RS_SingleMatch";
private static final String IMAGE_PATH = "imagePath";
private static final String IMAGE_NAME_PREFIX = "RideShareBuddyUserImage";
private Context context;
@SerializedName("id")
private int userId;
private int tripId;
private String imageUrl;
@SerializedName("userName")
private String email;
private String realName;
private String gender;
private int reputation;
private String createdAt;
private String birthdate;
private float fromLat, fromLon, toLat, toLon;
private String fromPOI, toPOI;
private String departureTime;
private int matchStrength;
// Constructor
public RS_SingleMatch(Context context) {
this.context = context;
}
// Constructor to use when reconstructing an object from a parcel
public RS_SingleMatch(Parcel in) {
readFromParcel(in);
}
@Override
public int describeContents() {
return 0;
}
@Override
// Called to write all variables to a parcel
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(userId);
dest.writeInt(tripId);
dest.writeString(imageUrl);
dest.writeString(email);
dest.writeString(realName);
dest.writeString(gender);
dest.writeInt(reputation);
dest.writeString(createdAt);
dest.writeString(birthdate);
dest.writeFloat(fromLat);
dest.writeFloat(fromLon);
dest.writeFloat(toLat);
dest.writeFloat(toLon);
dest.writeString(fromPOI);
dest.writeString(toPOI);
dest.writeString(departureTime);
dest.writeInt(matchStrength);
}
// Called from constructor to read object properties from parcel
private void readFromParcel(Parcel in) {
// Read all variables from parcel to created object
userId = in.readInt();
tripId = in.readInt();
imageUrl = in.readString();
email = in.readString();
realName = in.readString();
gender = in.readString();
reputation = in.readInt();
createdAt = in.readString();
birthdate = in.readString();
fromLat = in.readFloat();
fromLon = in.readFloat();
toLat = in.readFloat();
toLon = in.readFloat();
fromPOI = in.readString();
toPOI = in.readString();
departureTime = in.readString();
matchStrength = in.readInt();
}
// This creator is used to create new object or array of objects
public static final Parcelable.Creator<RS_SingleMatch> CREATOR = new Parcelable.Creator<RS_SingleMatch>() {
@Override
public RS_SingleMatch createFromParcel(Parcel in) {
return new RS_SingleMatch(in);
}
@Override
public RS_SingleMatch[] newArray(int size) {
return new RS_SingleMatch[size];
}
};
// Getters
public int getUserId() {
return userId;
}
public int getTripId() {
return tripId;
}
public String getImageUrl() {
return imageUrl;
}
public Bitmap getImage() {
Bitmap image = null;
// If imageUrl is not empty
if (getImageUrl().length() > 0) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this.context);
String imagePath = prefs.getString(IMAGE_PATH + getUserId(), "");
// Get image from cache
if ((image = RS_FileOperationsHelper.getImageAtPath(imagePath)) == null) {
Log.d(TAG, "Image not found on disk.");
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// If image not found on storage then download it
setImage(downloadImage(getImageUrl()));
}
});
t.start();
}
} else {
// Use default image
image = getDefaultProfileImage();
}
image = RS_ImageViewHelper.getRoundededImage(image, image.getWidth());
Log.d(TAG, "Image width : " + image.getWidth());
return image;
}
public String getEmail() {
return email;
}
public String getRealName() {
return realName;
}
public String getGender() {
return gender;
}
public int getReputation() {
return reputation;
}
public String getCreatedAt() {
return createdAt;
}
public String getBirthdate() {
return birthdate;
}
public float getFromLat() {
return fromLat;
}
public float getFromLon() {
return fromLon;
}
public float getToLat() {
return toLat;
}
public float getToLon() {
return toLon;
}
public String getFromPOI() {
return fromPOI;
}
public String getToPOI() {
return toPOI;
}
public String getDepartureTime() {
return departureTime;
}
public int getMatchStrength() {
return matchStrength;
}
// Setters
public void setContext(Context context) {
this.context = context;
}
public void setUserId(int userId) {
this.userId = userId;
}
public void setTripId(int tripId) {
this.tripId = tripId;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public void setImage(Bitmap img) {
if (img != null) {
// Get cache directory's path and append RIDESHARE_DIRECTORY.
String cacheDirStoragePath = context.getCacheDir()
+ "/"
+ RIDESHARE_DIRECTORY;
// Create directory at cacheDirStoragePath if does not exist.
if (RS_FileOperationsHelper
.createDirectoryAtPath(cacheDirStoragePath)) {
String imagePath = cacheDirStoragePath + "/"
+ IMAGE_NAME_PREFIX + this.userId + ".png";
// Save new image to cache
RS_FileOperationsHelper.saveImageAtPath(img, imagePath, this.context);
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(context);
Editor e = pref.edit();
e.putString(IMAGE_PATH + getUserId(), imagePath);
e.commit();
}
}
}
public void setEmail(String email) {
this.email = email;
}
public void setRealName(String realName) {
this.realName = realName;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setReputation(int reputation) {
this.reputation = reputation;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public void setFromLat(float fromLat) {
this.fromLat = fromLat;
}
public void setFromLon(float fromLon) {
this.fromLon = fromLon;
}
public void setToLat(float toLat) {
this.toLat = toLat;
}
public void setToLon(float toLon) {
this.toLon = toLon;
}
public void setFromPOI(String fromPOI) {
this.fromPOI = fromPOI;
}
public void setToPOI(String toPOI) {
this.toPOI = toPOI;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public void setMatchStrength(int matchStrength) {
this.matchStrength = matchStrength;
}
// calculates age using given date
@SuppressLint("SimpleDateFormat")
public int calculateAge(String date) {
int age = 0;
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date bdate = formatter.parse(date);
Calendar lCal = Calendar.getInstance();
lCal.setTime(bdate);
int lYear = lCal.get(Calendar.YEAR);
int lMonth = lCal.get(Calendar.MONTH) + 1;
int lDay = lCal.get(Calendar.DATE);
Calendar dob = Calendar.getInstance();
Calendar today = Calendar.getInstance();
dob.set(lYear, lMonth, lDay);
age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);
if (today.get(Calendar.DAY_OF_YEAR) < dob.get(Calendar.DAY_OF_YEAR)) {
age--;
}
} catch (ParseException e) {
e.printStackTrace();
}
return age;
}
// Download image if not available
protected void downloadAndSaveImage() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this.context);
String imagePath = prefs.getString(IMAGE_PATH + getUserId(), "");
File file = new File(imagePath);
// If image path not stored in user defaults or image does not exists
// then
if ((imagePath == null || !file.exists()) && this.imageUrl.length() > 0) {
// Download on separate thread
Thread t = new Thread(new Runnable() {
@Override
public void run() {
setImage(downloadImage(getImageUrl()));
}
});
t.start();
}
}
// Download an image
private Bitmap downloadImage(String imageUrl) {
Log.d(TAG, "Image url : " + imageUrl);
Bitmap image = null;
try {
// Download an image from url
InputStream in = new java.net.URL(imageUrl.trim()).openStream();
image = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
Log.d(TAG, "Image downloading complete. image : " + image);
return image;
}
// Get default image
protected Bitmap getDefaultProfileImage() {
Bitmap image = BitmapFactory.decodeResource(
this.context.getResources(), R.drawable.default_male);
if (this.gender.toUpperCase(Locale.US).startsWith("F")) {
image = BitmapFactory.decodeResource(this.context.getResources(),
R.drawable.default_female);
}
return image;
}
}
最佳答案
damian 发布的链接有助于解决我的问题。但是,在我的例子中,自定义对象中没有 View 组件。
根据我的观察,如果您发现 ANY_VARIABLE_NAME 有多个 JSON 字段
,那么很可能是因为 GSON 无法转换该对象。你可以尝试下面的代码来解决它。
添加下面的类来告诉 GSON 只保存和/或检索那些声明了序列化名称的变量。
class Exclude implements ExclusionStrategy {
@Override
public boolean shouldSkipClass(Class<?> arg0) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean shouldSkipField(FieldAttributes field) {
SerializedName ns = field.getAnnotation(SerializedName.class);
if(ns != null)
return false;
return true;
}
}
下面是您需要保存/检索其对象的类。为需要保存和/或检索的变量添加 @SerializedName
。
class myClass {
@SerializedName("id")
int id;
@SerializedName("name")
String name;
}
将 myObject 转换为 jsonString 的代码:
Exclude ex = new Exclude();
Gson gson = new GsonBuilder().addDeserializationExclusionStrategy(ex).addSerializationExclusionStrategy(ex).create();
String jsonString = gson.toJson(myObject);
从 jsonString 获取对象的代码:
Exclude ex = new Exclude();
Gson gson = new GsonBuilder().addDeserializationExclusionStrategy(ex).addSerializationExclusionStrategy(ex).create();
myClass myObject = gson.fromJson(jsonString, myClass.class);
关于java - 在共享首选项中保存自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19296404/
有谁知道如何使 DIV 的行为方式使其始终尝试占用其最大空间(无论内容如何)? 例如,如果我有一个 max-height 的 DIV的 600px和一个 min-height的 200px ,我怎样才
考虑两个表表A和表B 表A |id|driver_id|vehicle_id|is_allowed|license_number|driver_name| 表B |id|driver_id|vehic
对于 ASP.NET 应用程序,自定义脏话删除器/替换器的最佳实践实现方法是什么? 如果这是一个数据表解决方案,是否有免费的资源来获取数据? (类似于找到可以导入到系统中进行拼写检查的公共(publi
有很多 jquery 工具提示插件。 我应该使用哪一个?为什么? 最佳答案 我们使用过qTip在我们的一个项目中,因为它符合我们的所有要求,开发和维护良好,附带优秀的文档和已经很漂亮的模板,并且还为我
我在Internet上四处张望,找不到相关信息。我的程序需要向PowerShell配置文件中编写一些PowerShell代码。如果没有配置文件,我的程序将创建一个。问题是应使用哪种编码来创建Power
在 D、int、uint 中使用 foreach 时,循环索引的首选类型是什么?或者只是通过省略类型自动实现? 最佳答案 一般来说,索引应该是size_t。与长度相同。如果您尝试使用 int 或 ui
这个问题在这里已经有了答案: Repeat each row of data.frame the number of times specified in a column (9 个回答) 2年前关闭
已结束。此问题正在寻求书籍、工具、软件库等的推荐。它不满足Stack Overflow guidelines 。目前不接受答案。 我们不允许提出寻求书籍、工具、软件库等推荐的问题。您可以编辑问题,以便
关闭。这个问题需要多问focused 。目前不接受答案。 想要改进此问题吗?更新问题,使其仅关注一个问题 editing this post . 已关闭 8 年前。 Improve this ques
我有一个看起来像这样的字符串: "Element 1 | Element 2| Element 3: element 4" 我想对冒号后面的源字符串部分进行子串(到源字符串的末尾),但如果没有冒号,那
我接受任何解释语言 Perl、Python、Bash 等。但我更喜欢 Perl,因为它是我想要学习的。我有一个时间戳列表,例如: 17:31:16 17:31:16 17:31:18 17:31:29
我想在后台运行程序。首选 C#我想把图标放在托盘里。在指定的时间同步文件夹(我知道如何同步文件夹)。如何在后台运行它并开始同步(例如凌晨 2 点)? 最佳答案 您需要考虑使用 windows sche
我有一个 onChange 事件处理程序,它的结构如下: (e) => (value => this.setState(prevState => ({ form: {
我想在windows 7中捕获删除操作。如果用户从计算机上删除了文件,我需要在文件被删除时存储一条记录,以及删除了哪个文件。 一般文件操作,不针对特定文件夹或软件。所以假设用户从 d:\testFol
是否有任何库或开源函数可以近似通过以不规则间隔获取的一些值来描述的线下的面积? 首选 Action Script,但 Java 也可以正常工作。 最佳答案 您可以使用as3mathlib数学图书馆。这
对于我的网络应用程序,我希望提供给用户的图像具有响应性。此外,我还想在图像标签中指定 width 和 height 属性,这样在移动连接速度较慢的情况下,就不会出现浏览器重排。 是否可以通过使用纯 H
在展示公司 Logo 时,我今天看到了一些新东西。 他们在 h1 标签上设置了高度和宽度以及 overflow:hidden 并在 h1 标签内的 a 标签上设置了负边距以防止文本显示。 代码是这样的
我使用 Lucene 库开发了一个索引和搜索应用程序。但是这个库在我的上下文中在自定义排名方面有一些限制,除了它的性能之外,我需要可扩展性和访问各种词频等。是否有任何强大的开源全文库可用? 最佳答案
关闭。这个问题是opinion-based .它目前不接受答案。 想要改进这个问题? 更新问题,以便 editing this post 可以用事实和引用来回答它. 关闭 8 年前。 Improve
这是一个关于当我需要在列表中查找对象实例时如何实现 equals 方法的问题,该实例的值是我在其成员中拥有的实例之一。 我有一个实现了 equals 的对象: class User { pri
我是一名优秀的程序员,十分优秀!